Servidor WebSocket Node.JS simples

Agora vamos escrever um servidor WebSocket simples em node.js. Ao se conectar a este servidor, você receberá uma mensagem de boas-vindas em resposta. E também alguns comandos simples estarão disponíveis para execução.





Para fazer isso, você precisa instalar o Node.js com o gerenciador de pacotes npm, que vem com





Configuração do projeto

Primeiro, precisamos criar um diretório para o projeto futuro





mkdir websocket-server-node
      
      



Vá para o diretório





cd websocket-server-node
      
      



Em seguida, você precisa inicializar um novo projeto via npm





npm init
      
      



O instalador irá pedir-lhe para responder a algumas perguntas, você pode ignorá-las





, 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 , :





Mensagem: PONG





Chame a função wsSendEcho, por exemplo, com o conteúdo "Teste!", E o console produzirá:





Mensagem: Teste!





Isso é tudo! Quem gostou, colocou Like, se inscreve. Bom para todos!





Link para o código GitHub completo








All Articles