一、centos安装nodejs
Node.js v8.x安装命令
#curl --silent --location https://rpm.nodesource.com/setup_8.x | bash -
Node.js v7.x安装命令
#curl --silent --location https://rpm.nodesource.com/setup_7.x | bash -
Node.js v6.x安装命令
#curl --silent --location https://rpm.nodesource.com/setup_6.x | bash -
Node.js v5.x安装命令
#curl --silent --location https://rpm.nodesource.com/setup_5.x | bash -
用yum 安装 node.js
#yum install -y nodejs
二、安装nodejs-websocket
#npm install nodejs-websocket
三、服务器
nodejs代码,注意关闭防火墙。systemctl stop firewalld
vim test.js 编辑
node test.js 运行
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) {
console.log("收到的信息为:"+str)
if(str==="game1"){
game1 = conn;
game1Ready = true;
conn.sendText("success");
}
if(str==="game2"){
game2 = conn;
game2Ready = true;
}
if(game1Ready&&game2Ready){
game2.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建立完毕")
四、客户端
html页面运行
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) {
console.log("收到的信息为:"+str)
if(str==="game1"){
game1 = conn;
game1Ready = true;
conn.sendText("success");
}
if(str==="game2"){
game2 = conn;
game2Ready = true;
}
if(game1Ready&&game2Ready){
game2.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建立完毕")
服务器运行效果。
客户端运行效果。