【问题标题】:WebSocket on Node.js and share a message between all the connected clientsNode.js 上的 WebSocket 并在所有连接的客户端之间共享消息
【发布时间】:2012-09-04 04:50:51
【问题描述】:

我有一个带有 websocket 模块的 Node.js 服务器,通过以下命令安装:

npm install websocket

this guide开始,我决定扩展它在所有客户端之间共享发送的消息。

这是我的(简化的)服务器代码:

#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

var connectedClientsCount = 0; // ADDED
var connectedClients = []; // ADDED

wsServer.on('request', function(request) {
    var connection = request.accept('echo-protocol', request.origin);
    connectedClientsCount++;
    connectedClients.push(connection);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            for(c in connectedClients) // ADDED
                c.sendUTF(message.utf8Data); // ADDED
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        // here I should delete the client...
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

在这种情况下,我可以获得connectedClientsCount 值,但我无法管理connectedClients 列表。

我也尝试使用((eval)c).sendUTF(message.utf8Data); as for 声明,但它不起作用。

【问题讨论】:

  • 这只是问题中的拼写错误,还是您在 connectedClients/connectedclients 上使用了不同大小写的代码?
  • 我使用相同的大小写(现在编辑)...

标签: javascript json node.js websocket eval


【解决方案1】:

我建议您使用 Socket.IO:用于实时应用程序的跨浏览器 WebSocket。模块很简单install and configure

例如: 服务器

...
io.sockets.on('connection', function (socket) {
  //Sends the message or event to every connected user in the current namespace, except to your self.
  socket.broadcast.emit('Hi, a new user connected');

  //Sends the message or event to every connected user in the current namespace
  io.sockets.emit('Hi all');

  //Sends the message to one user
  socket.emit('news', {data:'data'});
  });
});
...

more

客户:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  //receive message
  socket.on('news', function (data) {
    console.log(data);
    //send message
    socket.emit('my other event', { my: 'data' });
  });
</script>

更多关于exposed events

【讨论】:

    【解决方案2】:

    尝试将for ... in 替换为for ... of

    for(c of connectedClients) // ADDED
        c.sendUTF(message.utf8Data); // ADDED
    

    【讨论】:

      猜你喜欢
      • 2016-12-26
      • 2017-05-26
      • 2019-09-20
      • 2014-09-18
      • 2021-08-16
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多