我在节点中有一个套接字服务器。恢复新消息时,会将其写入套接字。但是从中恢复过来的是写入到相应的套接字,而不是所有连接。
Server.js
var server = net.createServer(function(sock){
console.log('new client connected');
sock.on('data', function(data) {
console.log('Server received');
// ** NOT sending to all clients **
sock.write('broadcasting to others...');
});
});
Run Code Online (Sandbox Code Playgroud)
Client.js
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('Client connected to: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('Client is connected!!');
});
client.on('data', function(data) {
console.log('Client received: ' + data);
});
Run Code Online (Sandbox Code Playgroud)
如何将一条客户消息广播给所有其他客户?
遵循我的建议使用a Set来跟踪所有连接的套接字,这是一种实现方法。此实现Set通过侦听connect事件和end事件来维持连接的来来去去。
此实现还支持一种理想功能,该功能可以将触发事件的事件发送给所有连接的套接字(我认为这是您的情况所希望的):
// Set of all currently connected sockets
const connectedSockets = new Set();
// broadcast to all connected sockets except one
connectedSockets.broadcast = function(data, except) {
for (let sock of this) {
if (sock !== except) {
sock.write(data);
}
}
}
const server = net.createServer(function(sock){
console.log('new client connected');
connectedSockets.add(sock);
sock.on('end', function() {
connectedSockets.delete(sock);
});
sock.on('data', function(data) {
console.log('Server received');
connectedSockets.broadcast(data, sock);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
696 次 |
| 最近记录: |