Note that there are some explanatory texts on larger screens.

plurals
  1. POWebSocket on Node.js and share a message between all the connected clients
    primarykey
    data
    text
    <p>I've got a Node.js server with <code>websocket</code> module, installed through the following command:</p> <pre><code>npm install websocket </code></pre> <p>Starting from <a href="http://cjihrig.com/blog/creating-your-own-node-js-websocket-echo-server/" rel="nofollow">this guide</a>, I decided to extend it sharing the sent messages between all the clients.</p> <p>Here is my (simplified) server code:</p> <pre><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.'); }); }); </code></pre> <p>In this case I can get the <code>connectedClientsCount</code> value, but I can't manage the <code>connectedClients</code> list.</p> <p>I also tried with <code>((eval)c).sendUTF(message.utf8Data);</code> as for statement but it doesn't work.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload