NodeJS: Simple WebSocket with "ws" library

The npm package "ws" is a popular library for creating WebSockets servers and clients in Node.js. In this blog post, we'll explain how to use the "ws" package to create a simple WebSockets server and client in Node.js.

First, you'll need to install the "ws" package using npm. To do this, open a terminal and run the following command:

npm install ws

Next, we'll create a WebSockets server using the "ws" package. To do this, create a new JavaScript file and add the following code:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.
on('connection', function connection(ws) {
    ws.
on('message', function incoming(message) {
        console.log('received: %s', message);
    });

    ws.send('Hello World');
});

This code creates a new WebSockets server using the "ws" package and listens for incoming connections on port 8080. When a new connection is established, the server listens for incoming messages and logs them to the console. It also sends a message back to the client.

To create a WebSockets client, we can use the same "ws" package. Add the following code to your JavaScript file:

const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080');

ws.on('open', function open() {
    ws.send('hello, world!');
});

ws.on('message', function incoming(data) {
    console.log(data);
});

This code creates a new WebSockets client using the "ws" package and connects to the server we created earlier. When the connection is established, the client sends a message to the server and listens for incoming messages. When a message is received, it is logged to the console.

That's all there is to using the "ws" package to create a WebSockets server and client in Node.js. With just a few lines of code, you can easily add real-time communication capabilities to your Node.js applications.

Comments