Search code examples
tcpwebsocketporttcpsocket

How does a socket change ports from HTTP 80 to another port when we want to communicate over WebSocket using Javascript?


Let say I have a server XYZ that listens on port 50000 for TCP clients and port 80 for HTTP clients. And on the other side, I have a client that uses a WebSocket to establish a socket connection to port 50000 and will use HTTP port 80 for the handshake (of course).

Now, when the client begins, it will first send a request to server XYZ via the HTTP port 80, and the server will receive its request on port 80 for the handshake and will send a response for welcome. So, in that case, both parties are using port 80 (of course).

Now, when the handshake is done, the standard documentation says that the same TCP connection that is used for HTTP request/response for handshake purposes is then converted to the TCP socket connection. Ok right.

But, but if this whole handshake process and TCP connection for the HTTP request/response uses port 80 the first time, and that the same TCP connection is converted to the TCP socket connection, and this whole process is done via port 80, then how does the same TCP connection get converted to port 50000 for the TCP socket on both parties? Does the client initialize another TCP connection internally for changing to port 50000?

So, can anyone tell how the port conversion is performed and works in the WebSocket from port 80 to a different port in both parties? How does a complete single socket connection get established on the different ports? How does the same TCP connection change/flip its ports?


Solution

  • A TCP socket connection cannot change ports at all. Once a connection has been established, its ports are locked in and cannot be changed. If you have a TCP socket connection on port 80, the only way to have a connection on port 50000 is to make a completely separate TCP socket connection.

    A WebSocket cannot connect to port 80 and then switch to port 50000. However, an HTML page that is served to a browser from port 80 can contain client-side scripting that allows the browser to make a WebSocket object and connect it to port 50000. The two TCP connections (HTTP and WebSocket) are completely separate from each other (in fact, the HTTP socket connection does not even need to stay open once the HTML is served, since HTTP is a stateless protocol).