9951 explained code solutions for 126 technologies

nodejsHow to send message to client from websocket server

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

wss.on("connection", (ws,r) => {
  ws.send('This is a message to client');
});ctrl + c

import ws lib to create websocket server

new WebSocketServer.Server

create and launch websocket server with params


port to listen on (in our case all network interfaces are going to be listened)


what to do when someone connects to our server


send a message to client

This is a message to client

this message will be sent to websocket client