最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - WebSocket on Node.js and share a message between all the connected clients - Stack Overflow

programmeradmin2浏览0评论

I've got a Node.js server with websocket module, installed through the following mand:

npm install websocket

Starting from this guide, I decided to extend it sharing the sent messages between all the clients.

Here is my (simplified) server code:

#!/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.');
    });
});

In this case I can get the connectedClientsCount value, but I can't manage the connectedClients list.

I also tried with ((eval)c).sendUTF(message.utf8Data); as for statement but it doesn't work.

I've got a Node.js server with websocket module, installed through the following mand:

npm install websocket

Starting from this guide, I decided to extend it sharing the sent messages between all the clients.

Here is my (simplified) server code:

#!/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.');
    });
});

In this case I can get the connectedClientsCount value, but I can't manage the connectedClients list.

I also tried with ((eval)c).sendUTF(message.utf8Data); as for statement but it doesn't work.

Share Improve this question edited Sep 11, 2012 at 9:37 auino asked Sep 11, 2012 at 9:27 auinoauino 1,6565 gold badges23 silver badges44 bronze badges 2
  • Is it just a typo in the question, or do you use the code with different capitalization on connectedClients/connectedclients? – Eric Lennartsson Commented Sep 11, 2012 at 9:35
  • I use the same capitalization (edit now)... – auino Commented Sep 11, 2012 at 9:36
Add a ment  | 

2 Answers 2

Reset to default 6

I advise you to use Socket.IO: the cross-browser WebSocket for realtime apps. The module is very simple to install and configure

For example: Server

...
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

Client:

<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>

more about exposed events

Try replacing for ... in by for ... of

for(c of connectedClients) // ADDED
    c.sendUTF(message.utf8Data); // ADDED
发布评论

评论列表(0)

  1. 暂无评论