[英]How to echo all messages with “websockets/ws”
I'm using this websocket : https://github.com/websockets/ws and I want to send a message from one client to another. 我正在使用此websocket: https : //github.com/websockets/ws ,我想将消息从一个客户端发送到另一个客户端。 To begin with that, I wanted to echo the messages sent to the server, but the messages are just received by the client which has sent them.
首先,我想回显发送到服务器的消息,但是消息只是由发送它们的客户端接收的。 I know, that this works pretty easy with socket.io, but I have to use websockets/ws .
我知道,这在socket.io上非常容易,但是我必须使用websockets / ws。 This is my server code:
这是我的服务器代码:
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
ws.send(message); //This echoes the message
});
ws.send('Connection Opened');
});
You have to iterate over all the clients connected to the socket server. 您必须遍历连接到套接字服务器的所有客户端。 Replace your
ws.send(message);
替换您的
ws.send(message);
with 与
wss.clients.forEach(function(client) {
client.send(message);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.