websocket build service

Linking process

front end

1、CREATED WEBSOCKE

2、ONOPEN

3、ONMESSAGE

Server

1, received a request

2, the client sends a message id generated

//msg
{
    type: "id",
    id: Date.now() } 

front end

1, received messge, type for the id,

2, transmission message type = username of the message to the server, carrying the id

// clientID = msg.id
  var msg = {
    name: document.getElementById("name").value, date: Date.now(), id: clientID, type: "username" }; 

Server

1, received a username for the type of msg

2, set = connect.username  MSG.NAME ;

3, broadcast messages to other users type: "userlist",


var userListMsg = {
    type: "userlist",
    users: []
  };

4, message server sends usename

if (sendToClients) {
  var msgString = JSON.stringify(msg);
  var i;

  for (i=0; i<connectionArray.length; i++) { console.log(102, msgString); connectionArray[i].sendUTF(msgString); } } 

front end

1, the front end of the received message type = userlist, rendering a list of user 2, the front end of the received message type = username, rendering chat room message log

User lili signed in at 上午10:03:24
User hanmei signed in at 上午10:03:24

/**
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-02 16:17:14
 * @LastEditTime: 2019-09-04 10:16:54
 * @LastEditors: Please set LastEditors
 */

"use strict";

var https = require('http');
// var fs = require('fs');
var WebSocketServer = require('websocket').server;

var connectionArray = [];
var nextID = Date.now();
var appendToMakeUnique = 1;


// var httpsOptions = {
//   key: fs.readFileSync("/etc/pki/tls/private/mdn-samples.mozilla.org.key"),
//   cert: fs.readFileSync("/etc/pki/tls/certs/mdn-samples.mozilla.org.crt")
// };
 * @description create http server

/ **
 *
*/
var httpsServer = https.createServer(function(request, response) {
    console.log((new Date()) + " Received request for " + request.url);
    response.writeHead(404);
    response.end();
});

httpsServer.listen(6502, function() {
    console.log((new Date()) + " Server is listening on port 6502");
});


console.log("***CREATING WEBSOCKET SERVER");

/**
 *@description 创建WebSocketServer
 *
 */
var wsServer = new WebSocketServer({
    httpServer: httpsServer,
    autoAcceptConnections: false
});
console.log("***CREATED");

function originIsAllowed(origin) {
  // This is where you put code to ensure the connection should
  // be accepted. Return false if it shouldn't be.
  return true;
}

function isUsernameUnique(name) {
  var isUnique = true;
  var i;

  for (i=0; i<connectionArray.length; i++) {
    if (connectionArray[i].username === name) {
      isUnique = false;
      break;
    }
  }
  return isUnique;
}

function getConnectionForID(id) {
  var connect = null;
  var i;

  for (i=0; i<connectionArray.length; i++) {
    if (connectionArray[i].clientID === id) {
      connect = connectionArray[i];
      break;
    }
  }

  return connect;
}

function makeUserListMessage() {
  var userListMsg = {
    type: "userlist",
    users: []
  };
  var i;

  // Add the users to the list

  for (i=0; i<connectionArray.length; i++) {
    userListMsg.users.push(connectionArray[i].username);
  }

  return userListMsg;
}

function sendUserListToAll() {
  var userListMsg = makeUserListMessage();
  // console.log(111, userListMsg);

  var userListMsgStr = JSON.stringify(userListMsg);
  var i;
  // console.log(connectionArray);

  for (i=0; i<connectionArray.length; i++) {
    //立即将指定的字符串作为UTF-8 WebSocket消息发送给远程对等体
    console.log(100, userListMsgStr);

    connectionArray[i].sendUTF(userListMsgStr);
  }
}

console.log("***CRETING REQUEST HANDLER");


wsServer.on('request', function(request) {
  console.log("Handling request from " + request.origin);
  if (!originIsAllowed(request.origin)) {
    request.reject();
    console.log("Connection from " + request.origin + " rejected.");
    return;
  }

  // Accept the request and get a connection.

  var connection = request.accept("json", request.origin);

  // Add the new connection to our list of connections.

  console.log((new Date()) + " Connection accepted.");
  connectionArray.push(connection);
  // console.log(connectionArray);


  // Send the new client its token; it will
  // respond with its login username.

  connection.clientID = nextID;
  // console.log(connection.clientID);

  nextID++;

  var msg = {
    type: "id",
    id: connection.clientID
  };
  console.log(99, msg);

  connection.sendUTF(JSON.stringify(msg));

  /**
   * @description 接收消息
  */

  connection.on('message', function(message) {
    console.log("***Received MESSAGE*******", message);
      if (message.type === 'utf8') {
          // console.log("Received Message: " + message.utf8Data);ß

          // Process messages

          to true sendToClients = var; 
          msg = JSON.parse(message.utf8Data);
          // the console.log (1111, MSG); 

          var = getConnectionForID Connect (msg.id); 

          / ** 
           * @description received data 
          * / 

          Switch (msg.type) { 
            // Public Message text The Chat Room in 
            Case "Message": 
              MSG.NAME = connect.username; 
              msg.text msg.text.replace = (/ (<([^>] +)>) / IG, ""); 
              BREAK; 
            / * * 
             * @description login operation, inform others show 
            * / 
            // the username Change Request 
            Case "username": 
              var the nameChanged = false; 
              var OrigName = MSG.NAME;
              while (!isUsernameUnique(msg.name)) {
                msg.name = origName + appendToMakeUnique;
                appendToMakeUnique++;
                nameChanged = true;
              }
              if (nameChanged) {
                var changeMsg = {
                  id: msg.id,
                  type: "rejectusername",
                  name: msg.name
                };
                console.log(101,changeMsg);

                connect.sendUTF(JSON.stringify(changeMsg));
              }
              connect.username = msg.name;
              sendUserListToAll();
              break;
          }

          // Convert the message back to JSON and send it out
          // to all clients.
          /**
           * @desciption 发送给客户端消息
          */
          if (sendToClients) {
            var msgString = JSON.stringify(msg);
            var i;

            for (i=0; i<connectionArray.length; i++) {
              console.log(102, msgString);

              connectionArray[i].sendUTF(msgString);
            }
          }
      }
  });

  // Handle the WebSocket "close" event; this means a user has logged off
  // or has been disconnected.
  /**
   * @description 关闭socket
  */
  connection.on('close', function(connection) {
    // console.log(connectionArray);
    console.log(JSON.stringify(connection));
    console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");

    connectionArray = connectionArray.filter(function(el, idx, ar) {
      // console.log(el.connected);

      return el.connected;
    });
    sendUserListToAll();  // Update the user lists
    // console.log(connectionArray);

  });


});

console.log("***REQUEST HANDLER CREATED");

  

Reference article

Guess you like

Origin www.cnblogs.com/yiyi17/p/11457430.html