Middle
How does WebSocket differ from a regular socket?
sobes.tech AI
Answer from AI
WebSocket is based on TCP, like a standard socket, but provides full-duplex communication over an HTTP connection. A regular socket (for example, a TCP socket in Python) is a low-level interface for network interaction, requiring manual handling of the application layer protocol. WebSocket offers a standardized protocol that starts as an HTTP connection and then upgrades to the WebSocket protocol, allowing the server and client to exchange messages at any time without the need for constant requests (polling).
Main differences:
- Protocol: WebSocket is an application-level protocol for two-way communication, while a regular socket is an interface for working with the transport layer (TCP/UDP).
- Connection establishment: WebSocket uses HTTP for the handshake, then switches to its protocol. A regular socket establishes a connection directly (for example, using connect()).
- Bidirectionality: WebSocket is inherently full-duplex. With a regular socket, full-duplex communication is achieved by reading and writing to the same resource.
- Overhead: After establishing a connection, WebSocket has lower data transmission overhead compared to multiple HTTP requests or polling methods of regular sockets.
Example of establishing a WebSocket connection:
// Client sends an HTTP request to upgrade
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
// Server responds with a successful switch
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9lLkPxFuP5Gc7CD=
Example of using a regular TCP socket in Python:
import socket
# Create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server
s.connect(('localhost', 8080))
# Send data
s.sendall(b'Hello, server')
# Receive data
data = s.recv(1024)
# Close connection
s.close()