DEV Community

Cover image for Creating Websocket servers and clients in Nodejs
Onelinerhub
Onelinerhub

Posted on

1

Creating Websocket servers and clients in Nodejs

1. Websocket server example

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

wss.on("connection", (ws,r) => {
  ws.on("message", data => {
    ws.send('You sent me: ' + data);
  });

  ws.on("close", () => { });
  ws.onerror = function () { };
});
Enter fullscreen mode Exit fullscreen mode
  • require('ws') - import ws lib to create websocket server,
  • new WebSocketServer.Server - create and launch websocket server with params,
  • port: - port to listen on (in our case all network interfaces are going to be listened),
  • wss.on("connection" - what to do when someone connects to our server,
  • ws.on("message" - what to do when we've received a message from client,
  • ws.send( - send a message to client,
  • ws.on("close" - what to do when client closes connection,
  • ws.onerror - set custom error handler.

Open original or edit on Github.

2. Websocket client example

let ws = require('websocket');
let wsc = new ws.client;

wsc.on('connect', function(connection) {
  connection.sendUTF('Hello');

  connection.on('message', function(message) {
    console.log("Received: " + message.utf8Data);
    // connection.close();
  });
});

wsc.connect('ws://echoof.me:8111/');
Enter fullscreen mode Exit fullscreen mode
  • require('websocket') - import websocket lib to create websocket client,
  • new ws.client - create new websocket client object,
  • wsc.on('connect' - specify what to do when client gets connected to websocket server,
  • connection.sendUTF - send message to server,
  • connection.on('message' - specify what to do when client received message from server,
  • connection.close() - close connection (and exit),
  • wsc.connect - connect to websocket server,
  • echoof.me:8111 - public echo websocket server.

Open original or edit on Github.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more