尝试将socket.io-client连接到节点服务器我使用DEBUG = *
获得以下错误mocha:runner run suite Chat Server Message Events +1ms
Message Events
socket.io-client:url parse http://localhost:5000 +1s
socket.io-client ignoring socket cache for http://localhost:5000 +0ms
socket.io-client:manager readyState closed +1ms
socket.io-client:manager opening http://localhost:5000 +2ms
engine.io-client:socket creating transport "websocket" +1ms
engine.io-client:socket setting transport websocket +7ms
socket.io-client:manager connect attempt will timeout after 20000 +1ms
socket.io-client:manager readyState opening +1ms
engine.io-client:socket socket error
{"description":
{"code":"ENOENT",
"errno":"ENOENT",
"syscall":"connect",
"target":{"domain":null,
"_events":{},
"_maxListeners":10,
"_socket":null,
"_ultron":null,
"_closeReceived":false,
"bytesReceived":0,
"readyState":0,
"supports":{"binary":true},
"extensions":{},
"_isServer":false,
"url":"ws://localhost:5000/socket.io/?EIO=3&transport=websocket",
"protocolVersion":13,
"binaryType":"buffer"}}} +2ms
当我在浏览器上使用socket.io-client时,使用相同的套接字配置时,这种情况不会发生。
以下是测试代码:
var server = require('myServer');
var io = require('socket.io-client');
var url = 'http://localhost:5000';
var options = {
transports: ['websocket'],
'force new connection': true
};
var sender;
describe("Server Test", function () {
it('Should login user', function (done) {
sender = io(url, options);
});
});
这是服务器代码:
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log("connect");
});
server.listen(5000);
服务器正常运行。当scoket.io-client从浏览器运行但未在测试中时,它会显示日志消息。
有人能给我一个线索,为什么会这样?
答案 0 :(得分:0)
由于您正在测试,您可能在nodejs环境中定义了global.window。并且this代码行完全不期望它
您应该删除global.window对象或编写类似global.WebSocket = require('ws');
的内容或删除transports: ['websocket']