Simple Node.JS WebSocket Server

Now we will write a simple WebSocket server in node.js. When you connect to this server, you will receive a welcome message in response. And also a couple of simple commands will be available for execution.





To do this, you need to install Node.js with the npm package manager, it comes with





Project setup

First, we need to create a directory for the future project





mkdir websocket-server-node
      
      



Go to the directory





cd websocket-server-node
      
      



Next, you need to initialize a new project via npm





npm init
      
      



The installer will ask you to answer a few questions, you can skip them





, WS UTF-8





npm install ws
      
      



npm install --save-optional utf-8-validate
      
      



websocket-

. server.js, . , GitHub.





server.js:

websocket





const WebSocket = require('ws');
      
      



, , WebSocket, WebSocket-.





const wsServer = new WebSocket.Server({port: 9000});
      
      



HTTP-, WebSocket- . HTTP- , WebSocket- , .





, onConnect.





wsServer.on('connection', onConnect);
      
      



onConnection ws-, .





onConnect , wsClient. wsClient: message close.





message - .





close - .





onConnect, .





onConnect:





function onConnect(wsClient) {
  console.log(' ');
  //    
  wsClient.send('');
wsClient.on('message', function(message) {
    /*     */
  }
wsClient.on('close', function() {
    //    
    console.log(' ');
  }
}
      
      



close .





. , JSON-. JSON , .





JSON :





{
  action: 'ECHO' | 'PING',
  data?: string //  
}
      
      



, :





  • echo-, data





  • ping, pong





  • , " "





:





try {
  //   ,    JSON-
  const jsonMessage = JSON.parse(message);
  switch (jsonMessage) {
    case 'ECHO':
      wsClient.send(jsonMessage.data);
      break;
    case: 'PING':
      setTimeout(function() {
        wsClient.send('PONG');
      }, 2000);
      break;
    default:
      console.log(' ');
      break;
  }
} catch (error) {
  console.log('', error);
}
      
      



, PING , 2 .





server.js , , .





console.log('   9000 ');
      
      



:





node server.js
      
      



ws://localhost:9000. :





  • Windows Linux (Ctrl + C)





  • MacOs (Cmd + C)





,





Window:





ipconfig
      
      



Linux MacOS:





ifconfig
      
      



192.168.0.15, ws://192.168.0.15:9000.





, F12. DevTools, :





const myWs = new WebSocket('ws://localhost:9000');
//       
myWs.onopen = function () {
  console.log('');
};
//    
myWs.onmessage = function (message) {
  console.log('Message: %s', message.data);
};
//    echo-  
function wsSendEcho(value) {
  myWs.send(JSON.stringify({action: 'ECHO', data: value.toString()}));
}
//     ping  
function wsSendPing() {
  myWs.send(JSON.stringify({action: 'PING'}));
}
      
      



. wsSendPing:





wsSendPing()
      
      



2 , :





Message: PONG





Call the wsSendEcho function, for example, with the content "Test!", And the console will output:





Message: Test!





That's all! Who liked it, put Like, subscribe. Good to all!





Link to full GitHub code








All Articles