-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
92 lines (77 loc) · 1.92 KB
/
app.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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
// 引入http标准模块,CommonJS模块
const http = require("http");
const fs = require("fs");
const ws = require("socket.io");
const openUrl = require('./openUrl');
// 当前在线人数
let count = 0;
// 总访客人数
let totalCount = 0;
// 创建一个web服务器
const server = http.createServer(function(request, response) {
response.writeHead(200, {
"Content-Type": "text/html;charset=UTF-8"
});
// 可发送文本
// response.end("hello world");
// 可自动解析html
// response.end("<h1>我是标题2</h1>");
// 读取文件
const html = fs.readFileSync("index.html");
response.end(html);
});
// 基于当前web服务器开启socket实例
const io = ws(server);
// 检测连接事件
io.on("connection", function(socket) {
// console.log("当前有用户连接");
count++;
totalCount++;
// console.log("count:" + count);
let name = '';
// 给公众发送上线信息
// socket.broadcast.emit("connection", {
// count: count,
// id: count
// });
// 给自己发送上线信息
// socket.emit("connection", {
// count: count,
// id: totalCount
// });
// 加入群聊
socket.on("join", function(message) {
console.log(message);
name = message.name;
// console.log(name + "加入了群聊");
socket.broadcast.emit("joinNoticeOther", {
name: name,
action: "加入了群聊",
count: count
});
socket.emit("joinNoticeSelf", {
count: count,
id: totalCount
});
});
// 接收客户端所发送的信息
socket.on("message", function(message) {
console.log(message);
// 向所有客户端广播发布的消息
io.emit("message", message);
});
// 监听到连接断开
socket.on("disconnect", function() {
count--;
// console.log(name + "离开了群聊")
io.emit("disconnection", {
count: count,
name: name
});
});
});
// 服务器监听端口
const port = 3001;
server.listen(port);
console.log('Server has started.\n')
openUrl(`http://localhost:${port}`)