我的代碼依賴於在進行之前設置的其他代碼。在繼續之前,如何限制dom等待從服務器發送的東西?我已經嘗試了一段時間的聲明,並且最終導致「調用堆棧超出」異常。我也嘗試過setTimeOut,而render()將起作用,但我仍然會在render中得到一個異常,說明selfId還沒有定義。我怎樣才能解決這個問題?socket.io:如何確保設置值
舉例: 客戶:
<!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 });
});
你爲什麼不在'setSelf'裏面調用'gameLoop();''? – monkeyinsight
我嘗試了這一點,但是當我構建項目並首先打開服務器並嘗試在控制檯上回顯selfId時,它會顯示爲未定義。 爲什麼? – simon