-
Notifications
You must be signed in to change notification settings - Fork 50
/
server-close.js
45 lines (36 loc) · 1.08 KB
/
server-close.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
const net = require('node:net');
const server = net.createServer();
server.on('error', (err) => {
// 处理错误
throw err;
});
server.on('close', () => {
console.log('服务器接收到close事件');
})
server.on('connection', (socket) => {
console.log('服务器接收到connection事件');
socket.setEncoding('utf8');
socket.write('welcome!');
socket.on('data', (data) => {
console.log('服务器接收到的数据为:' + data);
// 如果收到c字符,就终止连接
if (data == 'c') {
socket.write('bye!');
socket.end(); // 关闭socket
// 如果收到k字符,就关闭服务器
} else if (data == 'k') {
socket.write('bye!');
socket.end(); // 关闭socket
server.close();// 关闭服务器
} else {
socket.write(data);
}
})
})
server.on('listening', () => {
console.log('服务器接收到listening事件');
})
// 绑定到端口
server.listen(8888, () => {
console.log('服务器启动,端口:8888');
});