Search code examples
c++socketswebsocketlistenwebsockify

How to run a socket and a websocket server on the same port?


I'm working on a server, which is listening on the port 80

I would like to enable both native and websocket clients to connect to my server.

It works only, if websockify runs at a different port, and forwards the trafic to the socket server.

Unfortunately websockify isn't well documented, and there are no tutorials available.

Where should I start, if I would like to create a single server only, which is listening on only one port, and accepts both websocket and native TCP sockets?


Solution

  • If your server is listening for connections on port 80, is it talking http? Because if not, don't be listening on port 80: Port 80 is well established as carrying http traffic.

    Next - an ipaddress and port together are the unique identifiers of an endpoint. If a remote client connects to your server on port 80, other than the destination ip and port there is no other information that the networking layer has to identify which application, listening on port 80, deserves the packet. Given that provisioning multiple ip addresses is quite hard - impossible over a NAT - the only information thats really available to route the packet to the correct listener is the port. So you just can not have two applications listening on the same port.

    Lastly websockets behave like native sockets, AFTER an initial HTTP negotiation. This means that, instead of using websocksify, you could teach your native server application to detect an attempt to connect by a websocket client and optionally perform the initial negotiation before going into 'native' mode.

    Writing Websocket Servers gives a brief breakdown of what your native server would need to implement.