What is WebSocket?
sobes.tech AI
Answer from AI
Application layer protocol that provides a bidirectional, full-duplex communication channel over a single TCP connection. Used for real-time applications: chats, online games, trading platforms.
Difference from HTTP:
- HTTP: client sends a request, server responds (unidirectional). Establishes a new connection for each request or reuses it via Keep-Alive.
- WebSocket: after connection establishment, client and server can send data at any time without re-establishing the connection (bidirectional).
Connection establishment:
HTTP is used for the initial "handshake". The client sends an HTTP request with headers Upgrade: websocket and Connection: Upgrade. The server responds with an HTTP response with status 101 Switching Protocols.
Data frames:
Data transfer occurs in the form of frames, allowing transmission of various data types (text, binary data).
Example of connection setup (schematic):
Client -> Server (Upgrade Request)
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Server -> Client (Upgrade Response)
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZgYesItU=
After this, WebSocket frame exchange begins.
Advantages:
- Low latency.
- Reduced server load (no need for constant polling).
- Ability to transmit data in real-time.
Disadvantages:
- Support needed on client and server sides.
- More complex implementation compared to simple HTTP requests.
In Java, libraries often used for WebSocket include:
- Java API for WebSocket (JSR 356).
- Spring WebSocket.
- Netty.