使用node.js如何简单快速的搭建一个websocket聊天应用

在这里插入图片描述

初始化项目

npm init

安装nodejs-websocket

npm install nodejs-websocket

创建并编辑启动文件

创建一个名为app.js文件,并且编辑它。

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

var [user1,user2,user1Ready,user2Ready] = [null,null,false,false];

ws.createServer(function(conn){
conn.on(“text”, function (str) {
console.log(“收到的信息为:”+str)
if(str===“user1”){
user1 = conn;
user1Ready = true;
}
if(str===“user2”){
user2 = conn;
user2Ready = true;
}
if(user2Ready){
user2.sendText(str);
}
if(user1Ready){
user1.sendText(str);
}
})
conn.on(“close”, function (code, reason) {
console.log(“关闭连接”)
});
conn.on(“error”, function (code, reason) {
console.log(“异常关闭”)
});
}).listen(8001)
console.log(“WebSocket建立完毕”)

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/119815873

posted @ 2022-06-03 17:55  忘川信使  阅读(102)  评论(0编辑  收藏  举报