user11909477
user11909477

Reputation:

Keep socket connection when new page is loaded

I have a small project with socket.io and node.js. Basically the landing page (index.html) is a waiting room for players, who can agree to play with each other. In that case, I want to redirect them to a different html (game.html, which is in the same folder as index.html). I want to keep the socket connection, since during the game there has to be communication with the server. I have tried two ways, but both fail. In each case, I change the client-side window.location (as described here).

1) In the javascript file of index.html, I have added an export of the socket object: export const socket = io(); Then I have imported this object in the other javascript file associated to game.html. But for some reason this doesn't work.

2) I have added another const socket = io(); in the javascript file associated to game.html. Then I can use that object. But as expected, this sets up a new connection and the previous connection is lost.

EDIT: I have asked the question also here in the comment. There I learnt that this issue is not really fixable. So I just render game.html inside of index.html (making DOM manipulations in main.js) for now.

Upvotes: 1

Views: 2083

Answers (3)

Jkm Show
Jkm Show

Reputation: 1

You can pass whole Socket to that route as param and there all the socket.io function will work as same as it

    const Room=({setSocket})=>{
var socket= useMemo(()=>(io.connect('http://localhost:5000')),[]);
    const value=useMemo(()=>(Math.floor(Math.random() * 9000) + 1000),[])
        socket.code = value
    setSocket(socket)
}

in app.is

<Route path ='/CreateRoom' element={<CreateRoom setSocket={setSocket}/>}/>

using state hook you can import in any route

Upvotes: 0

user11909477
user11909477

Reputation:

jfriend00 writes here:

This is how webSockets and socket.io connections work. They last ONLY for the duration of the page. When you go to a new URL and load a new page, the previous socket.io connection is closed and your code in the new page is free to make a new one. This is how things work in the browser.

Upvotes: 2

Mike B.
Mike B.

Reputation: 133

Martin, If you re-direct the client to a different endpoint then a new handshake with the server has to be initiated so you will get a new socket.id. What is the information that your server is emitting? Are you able to just re-render the DOM reflecting the new data instead of going to a completely different file? Would React's state management maybe mitigate your problem?

I might be able to help you if you can give me a code example.

Upvotes: 0

Related Questions