Java 套接字 + socket.io-客户端 (Angular 13) = 失败的连接和混乱的消息

Java Sockets + socket.io-client (Angular 13) = Failed connections and scrambled messages

我正在尝试将 Java 套接字服务器与 socket.io-client 一起使用,但从连接的那一刻起它就出现不稳定的行为。它设法建立连接,但随后在 Angular:

中抛出此异常
GET https://127.0.0.1:1532/socket.io/?EIO=4&transport=polling&t=N__rEfS net::ERR_SSL_PROTOCOL_ERROR

而Java中的服务器只会重复接收乱码

然后客户端开始一遍又一遍地连接和断开连接。为什么会这样?有什么方法可以使 Angular 13 到 Java 的 Socket 连接更清晰?

我将此 Java 套接字服务器用于许多其他应用程序,它非常适合除此之外的所有其他应用程序。

这是读取 Java 服务器的例程:

void handleClientRequest() {
    try{
        mBufferIn = new BufferedReader(new InputStreamReader( socket.getInputStream()));
        mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

        //in this while the client listens for the messages sent by the server
        while (clientRun) {

            String clientMessage = mBufferIn.readLine();

            if (clientMessage != null && mMessageListener != null) {

                mMessageListener.messageReceived(clientMessage);
            }
        }
    } catch(Exception e){
        System.out.printf("%s: Unexpected client disconnection. Reason:%n", accountId);
        e.printStackTrace();
    }
}

这是 Angular 代码:

this.socket = io('https://127.0.0.1:1532');

this.socket.on('connect', () => {
  const engine = this.socket.io.engine;
  console.log(engine.transport.name); // in most cases, prints "polling"

  engine.once('upgrade', () => {
    // called when the transport is upgraded (i.e. from HTTP long-polling to WebSocket)
    console.log(engine.transport.name); // in most cases, prints "websocket"
  });

  engine.on('packet', ({  }) => {
    // called for each packet received
  });

  engine.on('packetCreate', ({  }) => {
    // called for each packet sent
  });

  engine.on('drain', () => {
    // called when the write buffer is drained
  });

  engine.on('close', (reason: any) => {
    // called when the underlying connection is closed
  });
});

代码取自https://socket.io/docs/v4/client-socket-instance/

Socket IO是在websocket之上实现的一种通信协议 根据我的理解(如果我错了请纠正我)你在 java.

中使用原始套接字

您收到的“乱码”文本很可能是 https 握手的一部分。

我的建议是使用处理 websocket 连接的库。