Monday, 15 May 2017

NodeJS Socket.io server not receive message

I start create server with Nodejs and socket.io in simple way. In client connect just fine but when emit pong to server it never show. This code:

SERVER

var PORT = 3003;
var io = require('socket.io')(PORT);
var clients = [];
setInterval (function() {
    io.sockets.emit('ping');
}, 3000);
io.on('connection', (function(socket) {
    socket.emit ('welcome', { message: 'Connection complete', id: socket.id });
    clients.push ({id: socket.id, clientSocket: socket});
    print ('Client connected ' + socket.id);
    socket.on('disconnect', function() {
        clients.splice(clients.indexOf(socket), 1);
        print (socket.id + " is disconnected.");
    });
    socket.on('pong', function(args) {
        print (args + " is pong.");
    });
}).bind(this));
print('Server starting ...');

CLIENT:

var PORT = 3003;
var io = require('socket.io-client');
var socket = io.connect('http://localhost:' + PORT);
socket.on('connect', function(){
    print ('Client connected...');
});
socket.on('welcome', function(args) {
    print (args.message + ' / ' + args.id);
    // socket.disconnect();
});
socket.on ('ping', function(args) {
    socket.emit ('pong', { id: socket.id });
    print ('Receive ping...');
});
print ('Client Starting...');



via Cổ Chí Tâm

No comments:

Post a Comment