解决NodeJS Socket.io服务器无法接收消息

时间:2017-05-15 07:30:26

标签: node.js server socket.io client

我以简单的方式开始使用Nodejs和socket.io创建服务器。 在客户端连接就好了,但当发出pong到服务器它永远不会显示。 这段代码:

服务器

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 ...');

客户端:

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...');

0 个答案:

没有答案