# 退出时进行消息通知
- 服务端广播消息
- 客户端针对不同的业务进行代码提示
服务端:
ws.on('close', function () {
console.log('one client is closed :' + ws);
if (typeof ws.name !== 'undefined') {
// 广播到其他的客户端
wss.clients.forEach(function each(client) {
// 广播给非自己的其他客户端
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
name: ws.name,
event: 'logout',
num: wss.clients.size
}));
}
});
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
客户端:
// 客户端的代码
// 1. 发送消息
// 客户端 取input数据 -> websocket -> 发送到服务端 -> 转发给其他所有的客户端
// 2. 显示消息
var app = new Vue({
el: "#app",
data: {
isShow: true,
inputValue: "",
items: [],
wsHandle: "",
name: "",
num: 0,
},
// 把元素挂载完成之后,自动执行
mounted() {
var _this = this;
this.wsHandle = new WebSocket("ws://localhost:8000");
this.wsHandle.onopen = this.onOpen;
// 服务端发送回来的其他消息
this.wsHandle.onmessage = this.onMessage;
},
methods: {
submit: function() {
// 取inputValue
// 通过websocket发送数据
console.log(this.inputValue);
this.wsHandle.send(
JSON.stringify({
name: this.name,
message: this.inputValue,
event: "message",
})
);
this.items.push({
message: this.name + ": " + this.inputValue,
});
this.inputValue = "";
},
into: function() {
if (this.name.trim() === "") {
alert("用户名不得为空");
return;
}
this.wsHandle.send(
JSON.stringify({
name: this.name,
event: "login",
})
);
this.isShow = false;
},
onOpen: function() {
console.log("client is connected");
},
onMessage: function(evt) {
var msg = JSON.parse(evt.data);
if (msg.num) {
this.num = msg.num;
}
if (msg.event === "login") {
this.items.push({
message: "欢迎" + msg.name + "加入聊天室!",
});
} else if (msg.event === "logout") {
this.items.push({
message: msg.name + "已经退出了聊天室!",
});
} else {
if (msg.name !== this.name) {
// 把数据推送到items中
this.items.push({
message: msg.name + ": " + msg.message,
});
}
}
},
},
});
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79