websocket 服务搭建

链接过程

前端

1、CREATED WEBSOCKE

2、ONOPEN

3、ONMESSAGE

服务端

1、收到request

2、给客户端发送消息,生成id

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

前端

1、收到messge,type为id,

2、给服务端发送消息type=username的消息,携带id

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

服务端

1、收到type为username的msg

2、设置connect.username = msg.name;

3、广播给其他用户消息 type: "userlist",


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

4、服务端发送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);
  }
}

前端

1、 前端收到type=userlist的message,渲染用户列表 2、 前端收到type=username的message,渲染聊天室的登录消息

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 创建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

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

          var connect = getConnectionForID(msg.id);

          /**
           * @description 接收到的数据
          */

          switch(msg.type) {
            // Public text message in the chat room
            case "message":
              msg.name = connect.username;
              msg.text = msg.text.replace(/(<([^>]+)>)/ig,"");
              break;
            /**
             * @description 登录的操作,通知其他人展示
            */
            // Username change request
            case "username":
              var 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");

  

参考文章

posted @ 2019-09-04 10:25  地铁程序员  阅读(1287)  评论(0编辑  收藏  举报