Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Working with WebSocket using Nodejs
keshav Sandhu
keshav Sandhu

Posted on

Working with WebSocket using Nodejs

WebSockets provide a full-duplex, bidirectional communication channel over a single TCP connection, allowing real-time data exchange between clients and servers. They are commonly used in applications requiring low-latency, interactive communication, such as chat applications, online gaming, live notifications, and financial trading platforms.

InNode.js, WebSockets can be implemented using libraries such asws orSocket.IO. While WebSockets handle real-time communication over a persistent connection,Socket.IO offers a richer set of functionalities like reconnection and broadcasting.

Key Concepts in WebSockets

  • Persistent Connection: Once established, the WebSocket connection remains open, unlike traditional HTTP where a request-response is used for every communication.
  • Full-Duplex Communication: Data can be sent and received simultaneously between the client and server.
  • Low Overhead: Since there’s no constant opening/closing of connections, WebSockets are more efficient for real-time applications.
  • Event-Based Model: WebSockets operate using an event-based model where you can listen for events likemessage,open,close, anderror.

Installing WebSocket Library in Node.js

You can use thews library, which is a popular choice for WebSocket implementations in Node.js.

npminstallws
Enter fullscreen modeExit fullscreen mode

WebSocket Functions Usingws

1.Creating a WebSocket Server

constWebSocket=require('ws');// Create a WebSocket server on port 8080constwss=newWebSocket.Server({port:8080});wss.on('connection',ws=>{console.log('New client connected');// Listening for messages from the clientws.on('message',message=>{console.log(`Received:${message}`);// Echo the message back to the clientws.send(`Server:${message}`);});// Handling client disconnectionws.on('close',()=>{console.log('Client disconnected');});// Sending a message to the client on connectionws.send('Welcome to the WebSocket server!');});
Enter fullscreen modeExit fullscreen mode

2.Client-Side WebSocket Connection

In your client-side JavaScript (for example, inside an HTML file):

<script>constsocket=newWebSocket('ws://localhost:8080');socket.addEventListener('open',(event)=>{console.log('Connected to server');socket.send('Hello Server!');});socket.addEventListener('message',(event)=>{console.log('Message from server:',event.data);});socket.addEventListener('close',(event)=>{console.log('Connection closed');});</script>
Enter fullscreen modeExit fullscreen mode

3.Key WebSocket Functions

  • WebSocket Server Methods:

    • ws.on('connection', callback): Listens for new client connections.
    • ws.on('message', callback): Listens for incoming messages from a client.
    • ws.on('close', callback): Fires when a client disconnects.
    • ws.send(message): Sends a message to the connected client.
  • WebSocket Client Methods:

    • ws.send(data): Sends data to the server.
    • ws.on('open', callback): Fires when the connection to the server is established.
    • ws.on('message', callback): Fires when a message is received from the server.
    • ws.on('close', callback): Fires when the connection to the server is closed.

Common Use Cases of WebSockets

1.Chat Applications

Real-time chat applications require immediate communication between users. WebSockets allow sending and receiving chat messages in real-time without constantly polling the server.

2.Online Gaming

Multiplayer online games require fast and low-latency communication to ensure players have a smooth, interactive experience. WebSockets are used for sending in-game events, such as player movement and actions, between clients and the server.

3.Real-Time Notifications

WebSockets can be used to deliver real-time updates to users, such as notifications in social media apps, or updates in collaborative tools (e.g., Google Docs-style real-time editing).

4.Live Tracking

WebSockets are useful for applications like live location tracking (Uber, delivery apps) where users see real-time updates of a moving vehicle on a map.

5.Stock Price Tickers

For financial trading platforms or cryptocurrency exchanges, WebSockets enable real-time price updates for stocks, currencies, or other assets.

Simple WebSocket Project: Real-Time Chat Application

Project Structure:

|-- index.js (server)|-- public    |-- index.html (client)
Enter fullscreen modeExit fullscreen mode

1.Server-Side (Node.js + WebSocket):index.js

constWebSocket=require('ws');consthttp=require('http');constfs=require('fs');// Create HTTP server to serve the clientconstserver=http.createServer((req,res)=>{fs.readFile('./public/index.html',(err,data)=>{if(err){res.writeHead(500);returnres.end('Error loading file');}res.writeHead(200,{'Content-Type':'text/html'});res.end(data);});});constwss=newWebSocket.Server({server});wss.on('connection',ws=>{console.log('New client connected');// Broadcast message to all connected clientsws.on('message',message=>{console.log(`Received:${message}`);wss.clients.forEach(client=>{if(client!==ws&&client.readyState===WebSocket.OPEN){client.send(`Client says:${message}`);}});});// Send a welcome messagews.send('Welcome to the chat!');});server.listen(8080,()=>{console.log('Server is listening on port 8080');});
Enter fullscreen modeExit fullscreen mode

2.Client-Side (HTML + JavaScript):public/index.html

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>WebSocket Chat</title></head><body><h1>Real-Time Chat</h1><inputtype="text"id="message"placeholder="Type a message..."><buttononclick="sendMessage()">Send</button><ulid="messages"></ul><script>constsocket=newWebSocket('ws://localhost:8080');// Listen for messages from the serversocket.addEventListener('message',(event)=>{constmessageList=document.getElementById('messages');constnewMessage=document.createElement('li');newMessage.textContent=event.data;messageList.appendChild(newMessage);});functionsendMessage(){constmessageInput=document.getElementById('message');constmessage=messageInput.value;socket.send(message);messageInput.value='';}</script></body></html>
Enter fullscreen modeExit fullscreen mode

3.Running the Project

  • Start the WebSocket server by runningnode index.js.
  • Openlocalhost:8080 in a browser, and you'll be able to send and receive real-time messages using WebSockets.

Advanced Features with WebSockets

  • Authentication: Use authentication tokens or cookies to ensure only authorized users can establish WebSocket connections.
  • Broadcasting: In multi-client scenarios, messages sent by one client can be broadcast to all other clients using thews.clients set.
  • Reconnection: To handle disconnections, you can implement logic to automatically reconnect the WebSocket if the connection is lost (handled better with Socket.IO).
  • Compression: Use WebSocket extensions such aspermessage-deflate to compress data over the WebSocket, especially useful in low-bandwidth situations.

Conclusion

WebSockets in Node.js provide a powerful way to create real-time, low-latency communication channels. With libraries likews andSocket.IO, it's easy to build scalable applications like chat platforms, live notification systems, and real-time data feeds. Understanding the core functions and use cases helps you apply WebSockets in the right situations, especially for interactive or real-time applications.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

👋 Hi there! I'm a passionate developer with a love for solving challenging problems through code. I enjoy exploring new algorithms, optimizing solutions, and continuously learning about new techs.
  • Joined

More fromkeshav Sandhu

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp