-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
42 lines (37 loc) · 1.07 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
var ws = require("nodejs-websocket")
var port=3101;
var user=0;
// 创建一个连接
var server = ws.createServer(function (conn) {
console.log("创建一个新的连接--------");
user++;
conn.nickname="user" + user;
var mes = {};
mes.type = "enter";
mes.data = conn.nickname + " 进来啦"
broadcast(JSON.stringify(mes));
//向客户端推送消息
conn.on("text", function (str) {
console.log("回复 "+str)
mes.type = "message";
mes.data = conn.nickname + " 说: " + str;
broadcast(JSON.stringify(mes));
});
//监听关闭连接操作
conn.on("close", function (code, reason) {
console.log("关闭连接");
mes.type = "leave";
mes.data = conn.nickname+" 离开了"
broadcast(JSON.stringify(mes));
});
//错误处理
conn.on("error", function (err) {
console.log("监听到错误");
console.log(err);
});
}).listen(port);
function broadcast(str){
server.connections.forEach(function(connection){
connection.sendText(str);
})
}