use wss in nodejs app

use wss in node.js app

creare certificate

#生成私钥key文件
openssl genrsa 1024 > /path/to/private.pem
//
#通过私钥文件生成CSR证书签名
openssl req -new -key /path/to/private.pem -out csr.pem
//
#通过私钥文件和CSR证书签名生成证书文件
openssl x509 -req -days 365 -in csr.pem -signkey /path/to/private.pem -out /path/to/file.crt

then, this is my server.js

var https=require('https');
var ws=require('ws');
var fs=require('fs');
var keypath='private.pem';//我把秘钥文件放在运行命令的目录下测试
var certpath='file.crt';//console.log(keypath);
//console.log(certpath);
 
var options = {
  key: fs.readFileSync(keypath),
  cert: fs.readFileSync(certpath),
  passphrase:'1234'//如果秘钥文件有密码的话,用这个属性设置密码
};
 
var server=https.createServer(options, function (req, res) {//要是单纯的https连接的话就会返回这个东西
    res.writeHead(403);//403即可
    res.end("This is a  WebSockets server!\n");
}).listen(443);
    
wss = new ws.Server( { server: server } );

    chats = []; // 格式如room01:[client_connect1, client_connect2]}

wss.on('connection', function (connection) {
  //console.log(11111);
  connection.on('message', function (message) {
    var data;
    console.log(message); 
    try {
      data = JSON.parse(message);
    } catch (e) {
      console.log("Error parsing JSON:");
      console.log(message);
      data = {};
    }

    console.log(data.type);
    switch (data.type) {
      case "login":
        // 如果没有这个聊天室,就创建这个聊天室
        if(chats[data.chat_id] == undefined){
          chats[data.chat_id] = [];
        }
        console.log(Object.keys(chats[data.chat_id]));

        // 然后把自己的connection给到这个聊天室
        chats[data.chat_id][data.user_id] = connection;
        console.log(Object.keys(chats[data.chat_id]));


        console.log("user " + data.user_id + " login in chat " + data.chat_id )

        // 告诉这个聊天室中的所有的小伙伴们,我来了
        for(let key in chats[data.chat_id]) {
          var conn = chats[data.chat_id][key];
          if (conn != null) {
            try {
              sendTo(conn, {
                type: "someone_login",
                chat_id: data.chat_id,
                user_id: data.user_id, 
                user_name : data.user_name
              });
            } catch (error) {
              console.log("conn 已死,删除");
              delete chats[data.chat_id][key];
            }
          }
        }
        break;
      case "get_chat_users":
        console.log(data);
        // 给某个发送结果
        var conn = chats[data.chat_id][data.user_id];
        console.log(Object.keys(chats[data.chat_id]));
        if (conn != null) {
          try {
            sendTo(conn, {
              type: "chat_users",
              chat_id: data.chat_id,
              user_id: data.user_id, 
              users: Object.keys(chats[data.chat_id])
            });
          } catch (error) {
            console.log("conn 已死,删除");
            delete chats[data.chat_id][data.user_id];
          }
        }

        break;
      case "log_out":
        // 先把自己干掉
        delete chats[data.chat_id][data.user_id];
        console.log(Object.keys(chats[data.chat_id]));
        // 然后告诉伙伴们我走了
        for(let key in chats[data.chat_id]) {
          var conn = chats[data.chat_id][key];
          if (conn != null) {
            try {
              sendTo(conn, {
                type: "someone_log_out",
                chat_id: data.chat_id,
                user_id: data.user_id, 
              }); 
            } catch (error) {
              console.log("conn 已死,删除");
              delete chats[data.chat_id][key];
            }
          }
        }

        break;

    case "send_msg":
        // 给所有小伙伴发消息
        for(let key in chats[data.chat_id]) {
          var conn = chats[data.chat_id][key];
          if (conn != null) {
            try {
              sendTo(conn, {
                type: "someone_send_msg",
                chat_id: data.chat_id,
                user_id: data.user_id,
                user_name:data.user_name,
                msg: data.msg
              });
            } catch (error) {
              console.log("conn 已死,删除");
              delete chats[data.chat_id][key];
            }
          }
        }

        console.log("开发找系统聊天室");
        // 给所有小伙伴发系统消息
        for(let key in chats["sys_chat"]) {
          console.log(1);
          var conn = chats["sys_chat"][key];
          if (conn != null) {
            console.log(2)

            try {
              console.log(3)
              sendTo(conn, {
                type: "someone_send_msg",
                chat_id: "sys_chat",
                user_id: data.user_id,
                user_name:data.user_name,
                msg: data.chat_id + "@#$" +data.msg
              });
            } catch (error) {
              console.log("444444");
              delete chats["sys_chat"][key];
            }
          }
        }
    
        console.log("结束了");

        break;
      default:
        sendTo(connection, {
          type: "error",
          message: "Unrecognized command: " + data.type
        });

        break;
    }
  });

  connection.on('close', function () {
    
  });
});

function sendTo(conn, message) {
  //console.log(message);
  try {
    conn.send(JSON.stringify(message));
  } catch (error) {
    console.log("未预期的错误:");
    console.log(error);    
  }
}

wss.on('listening', function () {
    console.log("Server started...");
});

posted @ 2022-06-06 23:40  陆敏技  阅读(61)  评论(0编辑  收藏  举报
Web Counter
Coupon for Contacts