1
votes

I have a working socket.io server up and running, and i am trying to implement a server side socket.io client. Below is the code snippet i have been using for testing. The problem with this is that the client outputs the message only once, in this case it receives 'Welcome' only. I have tried sending messages to the private channel, 'message' via browser but it doesn't show any output even though the server can receive and emit the message successfully.

Client

    var io = require('socket.io-client');
    var socket = io.connect('http://localhost:3000', {'force new connection': true});
    socket.on('connect', function(){
            socket.on('message', function (data) {
                    console.log(data);
            });
    });

Server

    var io = require('socket.io').listen(server);
    var i=0;

    io.sockets.on('connection', function (socket) {
            socket.emit('message', { 'msg': 'Welcome'});
            socket.on('message', function (from, msg) {
                    socket.emit('message', { 'msg': 'Hello World -  ' + i });
                    i++;
            });
    });        
3

3 Answers

0
votes

Have you tried doing this?

console.log(data.msg);
0
votes

Can you try changing "socket" to "this":

this.emit('message', { 'msg': 'Hello World -  ' + i });
0
votes

You should emit from client side to server. So server can send the data back to client. I guess this code works fine :-)

Client

var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {'force new connection': true});
socket.on('connect', function(){

        socket.on('messageRecieved', function (data) {
                console.log(data);
        });

        socket.emit('message','some message');
});

Server

var io = require('socket.io').listen(server); 
var i=0;

io.sockets.on('connection', function (socket) {
        socket.on('message', function (msg) {
                console.log(msg);
                socket.emit('messageRecieved', { 'msg': 'Hello World -  ' + i });
                i++;
        });
});