nodejs 实现即时通讯 聊天室demo

需要安装 nodejs-Websocket

安装方法: https://www.npmjs.com/package/nodejs-websocket

服务端

var ws = require("nodejs-websocket");
console.log("开始建立连接...")

var game1 = null,game2 = null , game1Ready = false , game2Ready = false;
var server = ws.createServer(function(conn){
    conn.on("text", function (str) {
        
        if(str==="key1"){
            game1 = conn;
            game1Ready = true;
            conn.sendText("success");
        }
        if(str==="key2"){
            game2 = conn;
            game2Ready = true;
        }

        if(game1Ready&&game2Ready){
            game2.sendText(str);
            game1.sendText(str);
        }

        conn.sendText(str)//发送给客户端消息
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(8001)
console.log("WebSocket建立完毕")

客户端

 


第一次输入对方的key

send

 

你可能感兴趣的:(nodejs)