socket.io:如何确保设置值

时间:2016-09-24 03:22:01

标签: javascript websocket socket.io

我的代码依赖于在程序之前设置的其他代码。如何限制dom等待直到从服务器发送内容才继续?我尝试了一个while语句,最终得出“超出调用堆栈”的异常。我也试过setTimeOut,而render()将起作用,我仍然会在render中得到一个异常,说明selfId还没有定义。我该如何解决这些问题?

实施例: 客户端:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
        <link href="client/main.css" rel="stylesheet"</link>
    </head>
    <body>
        <div id="game">
            <!--GAMEBOARD-->
            <canvas id="ctx"></canvas>
            <!--CHATUI-->
            <div id="chat" class="chat">
                <div id="messages" class="messages">
                    <div>Welcome to Simon's Game Server</div>
                </div>
                <input id="chatinput" class="chatinput"></input>
            </div>
            <div id="fps"></div>
            <!--ADDITIONALUI-->
        </div>
        <script>
            var socket = io();
            //game loop
            var lastTime;
            function gameLoop() {

            }

            //init
            var selfId = null;   //How do i set this variable when the first user connects?  This is my question
            socket.on('setSelf', function (data) { //this is my attempt, but it is not working for the first user.
                console.log('Setting selfId to: ' + data.id);
                selfId = data.id;
                gameLoop();
            });

        </script>
    </body>
</html>

服务器:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var port = 1338;
var io = require('socket.io')(server);

//routes
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));

server.listen(port);


var UNIQUEID = 0;
io.sockets.on('connection', function (socket) {
    socket.myid = UNIQUEID;
    UNIQUEID++;
    socket.emit('setSelf', { id: socket.myid }); 
});

1 个答案:

答案 0 :(得分:0)

在Javascript中,你不能等待&#34;等等。或者&#34;睡眠&#34;直到事情发生。它不会那样工作。相反,您注册了某种事件处理程序,当发生这种情况时,您会触发相关代码。在你的情况下,你可以这样做:

var selfId = null;
socket.on('setSelf', function (data) {
     selfId = data.id;
     // don't call gameLoop until you get here and selfId is set
     gameLoop();
});

function gameLoop() {
    render();
    //....
    playerState();
    //
    //etc ....
    //
}

此外,在服务器上,您不应该覆盖socket.id,因为socket.io会将自己的ID硬币化,并将其用于自己的内务处理中。如果您想将某些内容存储在socket对象上,我建议您创建自己唯一的,不存在冲突的属性名称,例如.myId