乐闻世界logo
搜索文章和话题

Is it possible to use port 80 for both HTTP and web socket traffic?

1个答案

1

Yes, port 80 can be used simultaneously for HTTP and WebSocket communication. This is because the WebSocket protocol is designed to be compatible with HTTP. During the initialization phase of WebSocket communication, the connection is initiated via HTTP on the same port. This process is known as the handshake.

Handshake Process

The establishment of a WebSocket connection begins with an HTTP request that includes a special Upgrade header, indicating that the client wants to upgrade the connection from HTTP to WebSocket. This HTTP request looks like this:

shell
GET /chat HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Origin: http://example.com

If the server agrees to upgrade the protocol, it responds with an HTTP response as follows:

shell
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat

Simultaneous Use of HTTP and WebSocket

Once the WebSocket handshake is complete, the connection switches from HTTP to WebSocket, and subsequent data exchange is based on the WebSocket protocol. This means that although the initial handshake uses HTTP, once completed, the same port can be used for WebSocket communication without interfering with HTTP communication.

Practical Application Example

For example, a website might provide both standard HTTP web services and real-time chat functionality via WebSocket on port 80. Users can browse the website (via HTTP requests) while interacting with other users through real-time chat (via WebSocket), all through the same port.

Conclusion

Therefore, using port 80 to handle both HTTP and WebSocket communication is entirely feasible and very common in practical applications. This approach effectively utilizes network resources, simplifies network configuration, and ensures good compatibility and low latency.

2024年6月29日 12:07 回复

你的答案