Search code examples
node.jssocketswebsocketsocket.ioangular8

SocketIO closes connection with 'transport close' very frequently at client side


I've setup the socket.io-client v2.3.0 with my express server and I've been unable to trace the reason for disconnects at client side (Angular 8) having this error - "transport close". Below is the sample of my code -

Server:
var socketIO = require('socket.io');
var io = socketIO(server);

Client:
import * as io from 'socket.io-client';
private socket;
this.socket = io(url,{transports: ['websocket'], upgrade: false});
this.socket.on("disconnect", (reason)=> {console.log(reason)}); //prints "transport close"

The client reconnects just fine but it is causing a lot of inconvinience. Due to the "transport close" issue at the client, it is not able to receive some emits from the server causing the data integrity issue. Please tell me what could be the possible reason for this issue and if there is any work around to overcome this ?

I'm stuck on this issue since couple of days. Any help will be appreciated.

Thanks.


Solution

  • This question is a duplicate but i will post one of the solutions i found and hope it helps.

    Try to implement a heartbeat between server and client before the end of idle timeout.

    {transports: ["websocket"],
            pingInterval: 60000,
            pingTimeout: 60000,
            upgradeTimeout: 30000, ...}
    

    then

    setTimeout(() => this.sendHeartbeat(socket), 10000)
                socket.on("pong", (_data) => {})
    

    with

    private sendHeartbeat = (socket: socketIo.Socket) => {
        setTimeout(() => this.sendHeartbeat(socket), 10000)
        socket.emit("ping", { beat: 1 })
    }
    

    dont forget to implement the receiver client side. Using this i succeeded to avoid the transport close everytime the sockets goes on idle.

    let me know if it helps.