Sobes.tech
Junior

What is a WebSocket?

sobes.tech AI

Answer from AI

WebSocket is a protocol for two-way, full-duplex communication over a single TCP connection. It provides a persistent connection between client and server, allowing them to exchange data in real-time without the need for repeated requests.

Key features:

  • Low latency: Instant data transfer.
  • Efficiency: Less overhead compared to HTTP polling or long polling.
  • Two-way communication: The server can initiate sending data to the client.

Used in:

  • Chats
  • Online games
  • Trading platforms
  • Real-time notifications
  • Data streaming

Example of a simple WebSocket server in Python using the websockets library:

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        print(f"Received message: {message}")
        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()

Difference from HTTP:

Feature HTTP WebSocket
Connection Short-lived (on request) Persistent, two-way
Data exchange Client requests, server responds Two-way, at any time
Latency High (with polling) Low
Overhead Higher (for frequent requests) Lower
Examples Loading web pages, APIs Chats, real-time updates