我正在挖掘Socket.io文档,仍然无法弄清楚为什么io.sockets.on
不工作。我尝试过使用io.on
,但没有成功。
在客户端,我只是听听事件socket.on(ROUND_START/ROUND_END)
这个客户端监听器正在工作,但是,服务器一个 - io.sockets.on(ROUND_START...
- 不是。
服务器
/**
* Handle Game phases
*/
const NEXT_GAME_TIMEOUT = 5000;
const END_GAME_TIMEOUT = 10000;
const FULL_GAME_TIMEOUT = END_GAME_TIMEOUT + NEXT_GAME_TIMEOUT;
const ROUND_START = "ROUND_START";
const ROUND_END = "ROUND_END";
setInterval(() => {
io.sockets.emit(ROUND_START);
}, FULL_GAME_TIMEOUT);
// Not working
io.sockets.on(ROUND_START, () => {
console.log("ROUND STARTED")
setTimeout(() => {
io.sockets.emit(ROUND_END);
}, END_GAME_TIMEOUT)
});
io.sockets.on(ROUND_END, () => {
console.log("ROUND ENDED")
setTimeout(() => {
io.sockets.emit(ROUND_START);
}, NEXT_GAME_TIMEOUT)
});
不从客户端发送与循环启动相关的任何内容的想法是因为必须在套接字之间同步循环。
我究竟做错了什么?
我通常在套接字连接到服务器时附加。我在https://socket.io/get-started/chat上使用了聊天示例
完整的服务器配置
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
const NEXT_GAME_TIMEOUT = 5000;
const END_GAME_TIMEOUT = 10000;
const FULL_GAME_TIMEOUT = END_GAME_TIMEOUT + NEXT_GAME_TIMEOUT;
const ROUND_START = "ROUND_START";
const ROUND_END = "ROUND_END";
io.on('connection', function(socket) {
console.log("user connected!!!");
socket.on(ROUND_START, () => {
console.log("ROUND STARTED")
setTimeout(() => {
io.sockets.emit(ROUND_END);
}, END_GAME_TIMEOUT)
});
socket.on(ROUND_END, () => {
console.log("ROUND ENDED")
setTimeout(() => {
io.sockets.emit(ROUND_START);
}, NEXT_GAME_TIMEOUT)
});
})