MainExamplesHistoryRecommended Reading
Explain /Web Technology

What is WebSocket?

Help others learn from this page

WebSocket is a protocol that enables two-way, real-time communication between a client and server. Unlike HTTP where the client always initiates requests, WebSocket allows both sides to send messages anytime. It's like upgrading from walkie-talkies (HTTP) to a phone call (WebSocket) — you can talk and listen simultaneously.

How It Works:

  1. Handshake: Client sends HTTP request asking to upgrade to WebSocket
  2. Connection: Server accepts, connection upgrades to WebSocket
  3. Persistent: Connection stays open (unlike HTTP's request-response)
  4. Bidirectional: Both client and server can send messages
  5. Real-time: Messages arrive instantly

WebSocket vs HTTP:

  • HTTP: Request-response, client initiates, stateless
  • WebSocket: Persistent connection, bidirectional, stateful

When to Use WebSocket:

  • Real-time chat: Instant messaging
  • Live updates: Stock prices, sports scores
  • Collaborative editing: Multiple users editing together
  • Gaming: Real-time multiplayer
  • Notifications: Push notifications to browser

Benefits:

  • Low latency: No HTTP overhead per message
  • Efficient: Persistent connection, less overhead
  • Real-time: Instant communication

FAQ

When should I use WebSocket vs HTTP?
Use HTTP for request-response patterns. Use WebSocket when you need real-time, bidirectional communication or server-initiated messages.
Are WebSockets secure?
WebSocket (ws://) is not encrypted. Use WSS (WebSocket Secure, wss://) for encrypted connections, similar to HTTPS.

Enjoyed this explanation? Share it!

Promote your content

Reach over 400,000 developers and grow your brand.

Join our developer community

Hang out with over 4,500 developers and share your knowledge.