einaros/ws — pull request #212 by saschagehlich (2013-07-10 14:01:06+00:00)
Title: Race condition: Socket's first data event received before readyState is OPEN

I'm using socket.io and socket.io-client at the same time in my tests (socket.io-client uses `ws`) and I found a race condition in lib/Websocket.js.

On line 644 (master branch) we start listening to `data` events on the socket:

```js
socket.on('data', dataHandler);
```

But we set the readyState of our Websocket to `WebSocket.OPEN` later, on line 686:

```js
this.readyState = WebSocket.OPEN;
```

Now, I believe that if the client and the server live on the same process, they both handle the connection on the same tick, which results in a `dataHandler` call, even before `this.readyState` is set to open. This results in ws.onmessage not being called.

My solution is to start listening to data events on the next tick (see pull request) to make sure that our readyState has the right value.