简体   繁体   English

刷新/重新加载时socket.io“connect”事件不会触发

[英]socket.io “connect” event on refresh/reload wont fire

Having an issue with socket.io today. 今天遇到socket.io的问题。 When I refresh a page .on("connect", {}) never fires. 当我刷新页面时.on(“connect”,{})永远不会触发。 When I load a page from the url all events fire as they should. 当我从url加载页面时,所有事件均会触发。 As you can see below I set the gameStatus to broken. 如下所示,我将gameStatus设置为已损坏。 After a series of client/server communications the game status should update to "ready" and a new player should be created on the server. 在一系列客户端/服务器通信之后,游戏状态应更新为“就绪”,并且应在服务器上创建一个新玩家。 When I reload the page (cmd+r), none of the client side events fire. 当我重新加载页面(cmd + r)时,没有任何客户端事件触发。

The server side recognizes the new connection "sees" the new socket.id and emits the "send room" event, but the event is not received on the client side. 服务器端识别新连接“看到”新的socket.id并发出“发送房间”事件,但是在客户端没有收到该事件。

I tried to force new connection, but I don't know whether or not I am using that correctly. 我试图强制建立新的连接,但是我不知道我是否使用正确。

Last week this worked as I expected, then today without even updating the code, it can't get those events to fire on page refreshes. 上周这按照我的预期工作,然后今天甚至没有更新代码,它无法在页面刷新时触发这些事件。 Everything works as it should if I load the page from the full url ( http://localhost:3000 in this case) 如果我从完整的URL加载页面(在这种情况下为http://localhost:3000 ,一切都会正常进行

index.html: index.html的:

var io = io.connect('/', {'force new connection': true});

client.js client.js

var gameStatus = 'broken';
var localPlayer;

window.onload = function() {

  console.log(gameStatus);  // "broken"

  io.on("connect", onSocketConnected);
  io.on("disconnect", onSocketDisconnect);
  io.on("new player", onNewPlayer);
  io.on("send room", function(data){
        console.log("send room fired"); // doesn't fire on refresh
        addPlayer(data);
  });
}

function onSocketConnected() {
    console.log("Connected to socket server "); // doesn't connect on refresh
    // assign socket.sessionid as the player name
    localPlayer.id = io.socket.sessionid;
    io.emit("new player", {id: localPlayer.id});
    console.log(localPlayer.id); // "undefined" on refresh
}

function onSocketDisconnect() {
    console.log("Disconnected from socket server");
}

function addPlayer(data) {
    console.log("addPlayer fired"); // doesn't fire on refresh
    gameStatus = data.roomStatus;
}

server.js: server.js:

io.sockets.on('connection', function (socket) {

    socket.on("disconnect", onClientDisconnect);
    socket.on("new player", onNewPlayer);

});

io.sockets.on("connection", onSocketConnection);

function onSocketConnection(socket) {

    console.log("New player has connected: " + socket.id);
    var lastRoom = rooms.length-1;  // simplified for stackoverflow

    // send the playerType and roomNum to the client
    io.sockets.in(lastRoom).emit('send room', { roomStatus: "ready" });

}

function onNewPlayer(client) {

   console.log("new player created!"); // only on first page load

    var newPlayer = new Player(client.id); 
    players.push(newPlayer); // add player to player array
}

function onClientDisconnect(socket) {

    util.log("Player has disconnected: " + this.id);
    var disRooms = io.sockets.manager.roomClients[this.id];
    for (var room in disRooms) {
        if (room.length > 0) { // if not the global room ''
            room = room.replace(/\//g, '')
            console.log('user exits: '+room);
            this.broadcast.to(room).emit('player left');
        }
    }
}

After much gnashing of teeth, I discovered that the exposed "connect" method of socket.io fires before window.onload when a page is refreshed. 在咬牙切齿之后,我发现当刷新页面时,socket.io的暴露"connect"方法会在window.onload之前触发。 So my event handlers weren't set up by the time the server emits "connect." 因此,当服务器发出"connect."时,我的事件处理程序没有设置"connect." If the client misses that first "connect" everything else came apart. 如果客户端错过了第一次"connect"其他一切都分开了。 I fixed the problem by moving the event handlers out of window.onload. 我通过将事件处理程序移出window.onload来解决了该问题。

You might find other solutions, but this was mine: 您可能会找到其他解决方案,但这是我的:

var gameStatus = 'broken';
setEventHandlers();
console.log(gameStatus);  // "broken"

window.onload = function() {
    // other stuff
}

function setEventHandlers(){
  io.on("connect", onSocketConnected);
  io.on("disconnect", onSocketDisconnect);
  io.on("new player", onNewPlayer);
  io.on("send room", function(data){
        console.log("send room fired"); // fires as expected
        addPlayer(data);
  });
}

function onSocketConnected() {
    console.log("Connected to socket server "); // connects before window loads
    // assign socket.sessionid as the player name
    localPlayer.id = io.socket.sessionid;
    io.emit("new player", {id: localPlayer.id});
}

function addPlayer(data) {
    gameStatus = data.roomStatus;
    console.log(gameStatus);  // "ready"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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