我在节点中有一个套接字服务器。恢复新消息时,会将其写入套接字。但是从中恢复过来的是写入到相应的套接字,而不是所有连接。
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...');
});
});
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);
});
如何向所有其他客户端广播一条客户端消息?
答案 0 :(得分:4)
按照我的建议使用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);
});
});
答案 1 :(得分:1)
我相信,当每个客户端建立与服务器的连接时,您始终可以将每个客户端的套接字引用保留在数组中。要广播,只需循环数组并使用执行write()
var clients = [];
var server = net.createServer(function(sock){
console.log('new client connected');
clients.push(sock);
sock.on('data', function(data) {
console.log('Server received');
for(var i = 0; i < clients.length; i++) clients[i].write('broadcasting..');
});
});
或者,如果您同时拥有服务器和客户端的控制权,我认为最好使用websocket
或socket.io
,因为它具有广播功能。