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

What is WebSocket? How does it differ from HTTP?

2月18日 19:07

WebSocket is a network communication protocol that provides full-duplex communication capabilities over a single TCP connection. It is part of HTML5, allowing real-time, bidirectional interactive communication between servers and clients.

Core Features

  1. Full-duplex Communication: Both server and client can send and receive messages simultaneously
  2. Persistent Connection: Once established, the connection remains open until explicitly closed
  3. Low Latency: Reduces handshake and header overhead compared to HTTP polling
  4. Real-time: Server can proactively push data to clients

Differences from HTTP

  • HTTP is request-response model, WebSocket is bidirectional communication
  • HTTP connections are short-lived, WebSocket connections are persistent
  • HTTP requires complete headers for each request, WebSocket requires minimal data after connection establishment

Handshake Process

WebSocket connection is established through HTTP upgrade request:

  1. Client sends HTTP GET request with Upgrade: websocket header
  2. Server returns 101 Switching Protocols response
  3. Connection upgrades to WebSocket protocol

Use Cases

  • Real-time chat applications
  • Online gaming
  • Stock market data streaming
  • Collaborative editing
  • Real-time monitoring systems
标签:WebSocket