Websocket disconnects and connects every 30 seconds + sends messages randomly

99 views Asked by At

Screenshot of terminal logs

On the client side I use y-websocket and Y.js and the server side uses uWebsocket. Every 30 seconds the client disconnects and reconnects immediately afterwards. No messages should be sent except the inital one but it sends four messages for some reason after a while (read that it could be bcause of strict mode).

SERVER:

const app = uWs.App().ws('/*', {
    compression: 0,
    maxPayloadLength: 16 * 1024 * 1024,
    idleTimeout: 10,
    open: (socket) => {
        console.log('A user connected');
        c = new Date().getTime()/1000
    },
    message: (socket, message, isBinary) => {
        console.log(`Received message: ${message}`);
    },
    drain: (socket) => {
        console.log('Socket backpressure: ' + socket.getBufferedAmount());
    },
    close: (socket) => {
        console.log('A user disconnected');
        console.log("Time from connection: ", new Date().getTime()/1000 - c)
    }
}).listen(3000, (listenSocket) => {
    if (listenSocket) {
        console.log('Server listening on port 3000');
    }
});

CLIENT:

const yArray = useRef()
const wsProvider = useRef()

useEffect(() => {
    const ydoc = new Y.Doc();
    yArray.current = ydoc.getArray("lines")
    wsProvider.current = new WebsocketProvider('ws://localhost:3000', 'whiteboard', ydoc)
    }, [])

if(wsProvider.current){
    wsProvider.current.on('status', event => {
    console.log(event.status) // logs "connected" or "disconnected"
        })
    }

Changing the idleTimeout to 0 gives the same result. Should not be anything related to useEffect as it only renders once and the client does not currently do anything.

Tried reverting it back to version 1.3.8 which was the version that supposedly fixed it. Changing the idleTimeout to 120 which is the highest value doesn't change anything. I expect the connection to be established and keep connected until the client leaves/shuts down. All help is greatly appreciated!

1

There are 1 answers

0
iohn On BEST ANSWER
  const [{ store, ws }] = useState(() => {
    const store = syncedStore({
      item: [] as {
        item: string;
      }[],
    });

    const ws = new WebsocketProvider(
      "ws://localhost:3000",
      "test-room",
      getYjsDoc(store)
    );

    return { store, ws };
  });```

By using useState (should still only run once) and putting it in a syncedStore we managed to keep the connection from disconnecting. using useState instead of useEffect solved problem.