Creating chat with nodejs ws (einaros)

Yesterday I started using this module. I am trying to make a chat for something using websockets.

I have a problem: I do not know how to transfer a message that sends a client to the server, and then show it to all users. On the server side, I have this code:

var ipaddress = 'localhost';
var port = 8080;

var WebSocketServer = require('ws').Server
    , ws = new WebSocketServer({host:ipaddress, port:port});

ws.on('connection', function(ws) {
    console.log('New connection');
    ws.on('message', function(message) {
        ws.send(message);
    });
});

console.log('Listening to ' + ipaddress + ':' + port + ' ...');

And on the client side, this other code:

jQuery(document).ready(function($) {
    var content = $('#screen');
    var message = $('input[type="text"]').val();
    var ws = new WebSocket('ws://localhost:8080');

    ws.onopen = function() {
        console.log('Connected');
    };

    $('input[type="button"]').click(function() {
        ws.send(message);
    });

    ws.onmessage = function(msg) {
        console.log('Received message from server: ' + msg.data);
        addMessage(msg.data);
    }

    function addMessage(message) {
        content.prepend('<p><span>' + message + '</span></p>');
    }
});
+4
source share
2 answers

He explained here :

var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({host:ipaddress, port:port});

wss.broadcast = function(data) {
  for (var i in this.clients)
    this.clients[i].send(data);
};

// use like this:
wss.on('connection', function(ws) {
  ws.on('message', function(message) {
    wss.broadcast(message);
  });
});
+12
source
var WebSocketServer = require('ws').Server
var webserver = new WebSocketServer({ port:3000 });

webserver.on("message",function(message) {
    webserver.clients.forEach(function(client) {
        client.send(message);
    });  
}):
0
source

All Articles