简体   繁体   中英

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

I am trying to use a Java Socket Server with socket.io-client , but it has an erratic behavior from the moment of the connection. It manages to stablish connection, but then this exception is thrown in Angular:

GET https://127.0.0.1:1532/socket.io/?EIO=4&transport=polling&t=N__rEfS net::ERR_SSL_PROTOCOL_ERROR

And the Server in Java only receives scrambled text repatedly在此处输入图像描述

and the Client starts connecting and disconnecting over and over again. Why is this happening? Is there any way to get a cleaner Socket connection from Angular 13 to Java?

I use this Java Socket Server for many other applications and it works perfectly for everything else but this.

This is the routine that reads the Java Server:

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();
    }
}

And this is the Angular code:

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
  });
});

Code taken from https://socket.io/docs/v4/client-socket-instance/

Socket IO is a communication protocol implemented on the top of websocket from my understanding (correct me if im wrong) you are using raw socket in java.

So very likely that "scrambled" text that you are receiving, is part of https handshake.

My suggestion as way forward, will be to use library that handles websocket connections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM