问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/61697349/keep-socket-connection-when-new-page-is-loaded