客户端不会在 socketio 中发出事件

时间:2021-04-18 20:38:09

标签: node.js socket.io jestjs

我遵循了 socket.io 测试指南 here 它显示服务器发出一些事件并且客户端将接收它,但我希望它反过来。客户端应该发送一些数据,服务器会收到这是我的代码

  test("it should send valid file", (done) => {
    const id = "userId";
    const fileName = __dirname + "/videoTst.webm";
    
    serverSocket.on("receive_video_file", (data) => {
        console.log("called");
        expect(data.file).toEqual(prepareFile(fileName));
        expect(data.id).toEqual(id);
        done();
    });

    sendVideo(clientSocket, prepareFile(fileName), id, done);
    });

sendVideo 函数

const sendVideo = (socket: any, file: any, usrId: string, callback: any) => {
  socket.emit("receive_video_file", { file, id: usrId });
};

此结果超时错误,因为未收到事件或可能根本没有发出事件。我在回调函数中添加了一个控制台日志,但它没有被调用。

注意:当我尝试从服务器发送时

    serverSocket.emit("hello", {word: "world", file: prepareFile(fileName)});
    clientSocket.on("hello", (args: any) => {
      console.log(args);
      expect(args.word).toEqual("world");
      done();
    });

成功了! 我肯定在这里遗漏了一些东西。我对 socket.io 很陌生,所以我无法弄清楚。

更新:当我设置 DEBUG=socket.io:client*,socket.io:server* 时,我发现只发送了 type 0 条消息

$ jest
  socket.io:server initializing namespace / +0ms
  socket.io:server creating engine.io instance with opts {"path":"/socket.io"} +1ms
  socket.io:server attaching client serving req handler +1ms
  socket.io:server incoming connection with id uI2s4pGCSIJ5LiuFAAAA +34ms
  socket.io:client connecting to namespace / +0ms
  socket.io:client writing packet {"type":0,"data":{"sid":"OSg_9WK_p05JeRZCAAAB"},"nsp":"/"} +3ms
  socket.io:client client close with reason transport error +137ms
  socket.io:server incoming connection with id csCLNa-khLRO0xLNAAAC +1s
  socket.io:client connecting to namespace / +1s
  socket.io:client writing packet {"type":0,"data":{"sid":"aeyzUguWgcuJFZwFAAAD"},"nsp":"/"} +2ms
  socket.io:client client close with reason forced close +4s
 FAIL  test/unit/SendVideo/SendVideo.test.ts (10.496 s)

1 个答案:

答案 0 :(得分:0)

结果是 maxHttpBufferSize 而我的文件是 2MB。当我增加缓冲区大小时,它起作用了