我的代码依赖于在继续之前要设置的其他代码。我如何限制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 });
});
在Javascript中,你不能"Wait"或"Sleep"直到事情发生。事情不是这样的。相反,您可以注册某种事件处理程序,当发生这种情况时,您可以触发相关代码。在您的情况下,您可以这样做:
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
覆盖为套接字。IO创建自己的id,并在自己的内务管理中使用它。如果您想将某些内容存储为socket
对象的属性,我建议您创建自己唯一的,无冲突的属性名称,例如.myId
。