gpt4 book ai didi

node.js - 在 mocha 测试中无法将 socket.io-client 连接到服务器

转载 作者:搜寻专家 更新时间:2023-11-01 00:06:08 26 4
gpt4 key购买 nike

尝试将 socket.io-client 连接到 Node 服务器时,使用 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 从浏览器运行但不在测试中时,它会显示日志消息。

有人能告诉我为什么会这样吗?

最佳答案

由于您正在测试,您可能在 nodejs 环境中定义了 global.window。和 this代码行根本不期望它

您应该删除 global.window 对象或编写类似 global.WebSocket = require('ws'); 或删除 transports: ['websocket']

关于node.js - 在 mocha 测试中无法将 socket.io-client 连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38753786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com