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

时间:2013-12-09 21:08:00

标签: javascript node.js sockets socket.io page-refresh

今天遇到socket.io的问题。当我刷新页面时.on(“connect”,{})永远不会触发。当我从网址加载页面时,所有事件都会按照应有的方式启动。如下所示,我将gameStatus设置为已损坏。在一系列客户端/服务器通信之后,游戏状态应更新为“就绪”,并且应在服务器上创建新的播放器。当我重新加载页面(cmd + r)时,没有任何客户端事件触发。

服务器端识别新连接“看到”新的socket.id并发出“发送房间”事件,但是在客户端没有收到该事件。

我试图强制新连接,但我不知道我是否正确使用它。

上周这个按预期工作,然后今天甚至没有更新代码,它无法在页面刷新时触发这些事件。如果我从完整的URL(在这种情况下为http://localhost:3000)加载页面,一切都会正常工作

的index.html:

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

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:

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');
        }
    }
}

1 个答案:

答案 0 :(得分:7)

在咬牙切齿之后,我发现在刷新页面时,{。{1}}之前暴露的"connect" socket.io方法会触发。所以我的事件处理程序没有在服务器发出时设置window.onload如果客户端错过了第一个"connect."其他一切都分开了。我通过将事件处理程序移出window.onload修复了问题。

您可能会找到其他解决方案,但这是我的:

"connect"