如何使用“websockets / ws”回显所有消息

时间:2016-04-01 09:32:25

标签: javascript html websocket

我正在使用这个websocket:https://github.com/websockets/ws我希望从一个客户端向另一个客户端发送消息。首先,我想回应发送到服务器的消息,但消息只是由发送它们的客户端接收。我知道,使用socket.io这很容易,但我必须使用websockets / ws。 这是我的服务器代码:

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');
});

1 个答案:

答案 0 :(得分:0)

您必须遍历连接到套接字服务器的所有客户端。将您的ws.send(message);替换为

wss.clients.forEach(function(client) {
  client.send(message);
});