Sobes.tech
Junior — Middle

Explain the working principle of WebSocket and how it differs from standard HTTP connections.

sobes.tech AI

Answer from AI

WebSocket is a protocol that provides a full-duplex (two-way) persistent connection between a client and a server over a single TCP connection. Unlike standard HTTP, where the client sends a request and the server responds and then the connection is closed, WebSocket establishes a persistent connection, allowing both parties to exchange data at any time without re-establishing the connection.

Working principle:

  1. The client sends an HTTP request with the header Upgrade: websocket to initiate a WebSocket connection.
  2. The server confirms the switch to WebSocket, and the connection switches to a two-way mode.
  3. After establishing the connection, both parties can send messages in real-time.

Differences from HTTP:

  • HTTP is a request-response protocol, WebSocket is a persistent connection.
  • WebSocket reduces overhead for connection setup during frequent data exchange.
  • WebSocket is suitable for real-time applications: chats, games, trading terminals.

Example in Python using the websockets library:

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        await websocket.send(f"Echo: {message}")

start_server = websockets.serve(echo, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Explain the working principle of WebSocket and how it… - sobes.tech