WebSocket Implementation

Here we start implementing WebSockets for server communication.

We'll cover the following

As with any infrastructure-related code, middleware is the perfect place for our WebSocket implementation. Using middleware will allow us to catch any required actions sent over the network and dispatch anything coming from the server. The basic WebSocket setup is as follows:

// Basic structure of a WebSocket setup
const WS_ROOT = "ws://echo.websocket.org/";

const websocket = new WebSocket(WS_ROOT);

websocket.onopen    = () => {};
websocket.onclose   = () => {};
websocket.onerror   = event => {};
websocket.onmessage = event => {};

To make the code more readable, we can replace the four different assignments with a single use of Object.assign() and use code similar to this:

Object.assign(websocket, {
  onopen()     { },
  onclose()    { },
  onerror(e)   { },
  onmessage(e) { }
});

In our middleware, we want to make sure a WebSocket is only created once. Thus, we cannot put the setup code inside the action handler:

// The wrong way to initialize in middleware
const wsMiddleware = ({ dispatch, getState }) => next => action => {
  // Initialization not allowed
};

The code in the innermost block gets called every time we dispatch an action, so this would cause our setup and WebSocket creation code to be called multiple times. To prevent this, we can do the initialization outside the action callback block:

// The correct way to initialize in middleware
const wsMiddleware = ({ dispatch, getState }) => next => {

  // TODO: Initialization

  return action => {
    // TODO: Middleware code
  };
};

Get hands-on with 1200+ tech skills courses.