1/*
2 * Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd.
3* Licensed under the Apache License, Version 2.0 (the "License");
4* you may not use this file except in compliance with the License.
5* You may obtain a copy of the License at
6*
7*     http:*www.apache.org/licenses/LICENSE-2.0
8*
9* Unless required by applicable law or agreed to in writing, software
10* distributed under the License is distributed on an "AS IS" BASIS,
11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12* See the License for the specific language governing permissions and
13* limitations under the License.
14 */
15// 模拟流媒体服务,两个client互相发送音频数据
16
17const net = require('net');
18
19const HOST = '127.0.0.1';
20const PORT = 8979;
21
22const server = net.createServer();
23server.listen(PORT, HOST);
24console.log('服务端已启动');
25const clients = {}; //保存客户端的连接
26
27// 重要:双方建立链接时,会自动获得一个socket对象(std,socket描述符)
28server.on('connection', (socket) => {
29  onAccept(socket)
30});
31
32function onAccept(client) {
33  // 远程客户端地址
34  console.log(`connected:${client.remoteAddress}:${client.remotePort}`);
35  delete clients[client.remoteAddress+client.remotePort];
36  clients[client.remoteAddress+client.remotePort] = client;
37  console.log(`当前客户端连接数:${Object.keys(clients).length}`);
38  // 收到客户端数据时
39  client.on('data', (data) => {
40    broadcast(data, client)
41  });
42  // 客户端主动断连,触发end事件
43  client.on('end', () => {
44    console.log(`客户端${client.remoteAddress}:${client.remotePort}已断连`);
45  });
46  client.on('close', (hadError) => {
47    console.log(`客户端${client.remoteAddress}:${client.remotePort}已关闭`);
48    delete clients[client.remoteAddress+client.remotePort];
49    console.log(`当前客户端连接数:${Object.keys(clients).length}`);
50  });
51
52  client.on('error', (err) => {
53    console.log(`客户端错误 ${JSON.stringify(err)}`);
54  });
55}
56
57/**
58 * 广播消息
59 */
60function broadcast(msg, self) {
61  Object.keys(clients).forEach((ip) => {
62    if (clients[ip].remoteAddress + clients[ip].remotePort != self.remoteAddress + self.remotePort) {
63      clients[ip].write(msg);
64    }
65  });
66}