npm install http --save
npm install websocket --save

Server.js
      const http = require('http');
      const wsServer = require('websocket').server;
      
      var socket = new wsServer({
          httpServer: http.createServer().listen(8000)
      });
      socket.on('request', function(request) {
          var conn = request.accept(null, request.origin);
          console.log('connected');
          conn.on('message', function(message) {
              message_handler(message);
          });
          conn.on('close', function(conn) {
              console.log('connection closed');
          });
      });
      
      function message_handler(message){
          var data = JSON.parse(message.utf8Data);
          console.log("name->" + data.name);
          console.log("ssid->" + data.ssid);
      }
	
Test.html
      <!DOCTYPE html>
      <html>
          <head>
              <meta charset="utf-8">
              <meta name="viewport" content="width=device-width">
              <title>Websocket Example</title>
              <script src="//code.jquery.com/jquery-3.1.1.min.js" type="text/javascript"></script>
              <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
              <script>
              var i = 0;
              var socket = null;
              var handler = null;
              function websocket_create(){
                  socket = new WebSocket('ws://localhost:8000');
                  socket.onopen = function () {
                      handler = setInterval(function(){
                          i++;
                          console.log(i);
                          socket.send(JSON.stringify({ name:'Peter', ssid: 102267002 }));
                      },5000);
                  };
                  socket.onmessage = function (message) {
                      message_handler(message);
                  };
                  socket.onerror = function (error) { };
                  socket.onclose = function (close) {
                      clearInterval(handler);
                      setTimeout(websocket_create, 1000);
                  };
              }
              function message_handler(message){
                  var data = JSON.parse(message.utf8Data);
                  console.log("name->" + data.name);
                  console.log("ssid->" + data.ssid);
              }
              setTimeout(websocket_create, 0);
              </script>
          </head>
          <body></body>
      </html>
	

酷米 © All Rights Reserved.

loading
Loading...