Middle
Why is WebSocket needed if HTTP exists? What is the main difference?
sobes.tech AI
Answer from AI
WebSocket is needed for bidirectional persistent communication between the client and server, whereas HTTP is a request-response protocol where the client initiates each request.
Main difference:
- HTTP: the client sends a request, the server responds, and the connection is closed.
- WebSocket: a persistent connection is established, over which both parties can send data at any time.
This is important for real-time applications, such as chats, games, financial trading platforms.
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}")
asyncio.get_event_loop().run_until_complete(
websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()