Search code examples
node.jswebsocketsocket.iowebsockify

Connecting Nodejs tcp server to a websockit


I'm trying to connect my node tcp server to my socket.io server using websockify in javascript. I found the git repo for it at https://github.com/novnc/websockify/wiki/websock.js , but can't seem to find how to start it off in code. Can anyone provide an example or point me to some kind of documentation for the js version? Also, when I download websockify off of npm, I don't receive websock.js, if anyone can tell how to do that too I'd appreciate it.


Solution

  • A socket.io server can only talk to a socket.io client. So, you cannot connect a plain TCP server to a socket.io server. To connect to a socket.io server, you need a socket.io client. You can certainly get the socket.io-client for node.js and then you can use that to connect to a socket.io server.

    Let me explain a bit. socket.io is built on top of webSocket and has it's own connection initiation on top of webSocket. webSocket uses HTTP to initiate a connection and then after some connection handshaking switches to the webSocket protocol. If any of those pieces are missing, the connection will fail to get established and/or will shut-down shortly after connecting.

    So, to connect to a socket.io server, all of the following has to happen:

    1. A socket.io client connection request must be initiated.
    2. That will make an HTTP request to the socket.io server and send some custom data.
    3. After some initial back-and-forth, the socket.io client will initiate a webSocket connection as the main transport.
    4. That webSocket connection will start with a custom HTTP request with an upgrade header that specifies a request to "upgrade" to the webSocket protocol and it will also contain some custom headers used in webSocket security.
    5. The server responds affirmatively to the upgrade request and also returns some security-related headers.
    6. The protocol is switched from HTTP to webSocket.
    7. All communication on this socket now uses the webSocket data frame format and associated webSocket security.
    8. Now, when socket.io wants to send data over this connection it adds its own higher level packet format on top of the webSocket data frame format.

    So, only a socket.io client, using a supported transport (typically webSocket) can connect to a socket.io server. You can't use a webSocket client to connect to a socket.io server. You can't use a plain TCP client. You can't use an HTTP client.