我构建了一个简单的Node socket.io服务器和两个简单的Node socket.io客户端。每个客户端连接到服务器,发送单个请求,等待响应并打印它。问题是,每个响应打印两次,因为每个客户端不仅获得自己的响应,还获得另一个客户端的响应!为什么呢?
这是服务器代码:
var io = require('socket.io').listen(10001);
io.sockets.on('connection', function (socket) {
socket.on('echo', function (data) {
console.log("got request to echo "+data);
socket.emit("echoes", data+" "+data);
});
});
以下是客户端代码:
var socketioclient = require('socket.io-client');
var socket1 = socketioclient.connect(HOST, {port: PORT});
var socket2 = socketioclient.connect(HOST, {port: PORT});
socket1.on('connect', function () { console.log("socket1 connected!"); });
socket2.on('connect', function () { console.log("socket2 connected!"); });
socket1.on('echoes', function (result) { console.log("socket1 received: "+result); });
socket2.on('echoes', function (result) { console.log("socket2 received: "+result); });
socket1.emit('echo', "aaa");
socket2.emit('echo', "bbb");
这是客户端输出:
socket1 connected!
socket2 connected!
socket1 received: aaa aaa
socket2 received: aaa aaa
socket1 received: bbb bbb
socket2 received: bbb bbb
这是服务器日志:
info - socket.io started
debug - client authorized
info - handshake authorized niJGX0EXWvLPw2THZOeD
debug - setting request GET /socket.io/1/websocket/niJGX0EXWvLPw2THZOeD
debug - set heartbeat interval for client niJGX0EXWvLPw2THZOeD
debug - client authorized for
debug - websocket writing 1::
got request to echo aaa
debug - websocket writing 5:::{"name":"echoes","args":["aaa aaa"]}
got request to echo bbb
debug - websocket writing 5:::{"name":"echoes","args":["bbb bbb"]}
debug - emitting heartbeat for client niJGX0EXWvLPw2THZOeD
debug - websocket writing 2::
debug - set heartbeat timeout for client niJGX0EXWvLPw2THZOeD
debug - got heartbeat packet
debug - cleared heartbeat timeout for client niJGX0EXWvLPw2THZOeD
debug - set heartbeat interval for client niJGX0EXWvLPw2THZOeD
debug - emitting heartbeat for client niJGX0EXWvLPw2THZOeD
debug - websocket writing 2::
debug - set heartbeat timeout for client niJGX0EXWvLPw2THZOeD
答案 0 :(得分:3)
默认情况下,socket.io
客户端将重用同一客户端到同一主机/端口(doc)的现有连接。您可以使用force new connection
选项禁用此行为:
// client.js
var socket1 = socketioclient.connect(HOST, {port: PORT, 'force new connection': true });
var socket2 = socketioclient.connect(HOST, {port: PORT, 'force new connection': true });