WebSockets in JavaScript: When a "Live" Site Is Not Magic, But Code
\n\nHave you ever wondered how online chats, real-time stock quotes, or multiplayer browser games work? The secret is simple and elegant — WebSockets in JavaScript. This technology turns a static website into a living organism that instantly reacts to the actions of other users.
\n\nIn this article, we won't just cover the theory. We'll write a real chat from scratch, learn how to handle errors, and understand why real-time applications on WebSockets work faster than the good old AJAX with polling. Buckle up — it's going to be interesting.
\n\nWhy HTTP Is Not Suitable for Real-Time? (A Quick Primer)
\n\nRegular HTTP works on a "request-response" principle. The client asks — the server answers. If the server wants to say something on its own (e.g., "a new message has arrived"), it has to wait until the client asks again. This is reminiscent of communicating by carrier pigeons — slow and inefficient.
\n\nDevelopers have come up with workarounds:
\n- \n
- Polling — the client pings the server every 5 seconds: "So, any news?" \n
- Long polling — the server keeps the connection open until a response is available (but it's still a one-way channel). \n
And then WebSockets enter the scene. Imagine you've opened a telephone line between the browser and the server. Both can speak at any time, simultaneously, without delays for "picking up the receiver." That's the magic of the JavaScript WebSocket API.
\n\nHow WebSocket Works: Protocol, Handshake, Messages
\n\nTechnically, WebSocket is a separate protocol (ws:// or wss:// for encrypted connections). It all starts with an HTTP handshake:
\n\n- \n
- The client sends a regular HTTP request with the header
Upgrade: websocket. \n - The server responds: "101 Switching Protocols" — and the connection is "upgraded" to WebSocket. \n
- After that — full duplex: data flies in both directions in the form of frames (text or binary data). \n
In the browser, the built-in WebSocket object is used to work with WebSocket. No additional libraries are needed — pure JavaScript WebSocket works out of the box in all modern browsers.
Writing Your First Real-Time Chat in JavaScript
\n\nLet's create a simple chat. We'll write the server part using Node.js with the ws library (the most popular for WebSocket Node.js), and the client in pure JavaScript.
Step 1. Server Setup
\n\nnpm init -y\nnpm install ws\n\nStep 2. Server Code (server.js)
\n\nconst WebSocket = require('ws');\n\nconst wss = new WebSocket.Server({ port: 8080 });\n\nwss.on('connection', function connection(ws) {\n console.log('New user connected');\n\n // Send a welcome message to the new client\n ws.send(JSON.stringify({\n type: 'system',\n message: 'Welcome to the chat!'\n }));\n\n // Receive messages from the client\n ws.on('message', function incoming(data) {\n const message = JSON.parse(data);\n console.log('Received:', message);\n\n // Broadcast the message to all connected clients\n wss.clients.forEach(function each(client) {\n if (client.readyState === WebSocket.OPEN) {\n client.send(JSON.stringify({\n type: 'message',\n user: message.user,\n text: message.text,\n time: new Date().toLocaleTimeString()\n }));\n }\n });\n });\n\n // Handle disconnection\n ws.on('close', function() {\n console.log('User disconnected');\n });\n});\n\nconsole.log('Server running on ws://localhost:8080');\n\n