我正在尝试使用 node.js
制作游戏服务器, socket.io
.
基本思想如下。
socket.io
服务器启动时的实例socket.io
Controller 中的事件或其他一些点这是我所做的实现......
首先,在
server.js
- 入口点let GlobalVars = require('./state/GlobalVars');
const apiRouters = require('./router');
...
app.use('/api', apiRouters);
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/test/simpleClient.html`)
});
const httpServer = http.createServer(app);
let socketIOInstance = socketIO(httpServer);
socketIOInstance.on('connection', (socket) => {
console.log('SOCKET.IO A USER CONNECTED');
socket.on('create', (data) => {
console.log('SOCKET.IO create called', socket);
socket.join(data.room);
socketIOInstance.emit('message', 'New people joined');
});
socket.on('join', (data) => {
console.log('SOCKET.IO join called', data);
})
socket.emit('message', 'Hi');
});
GlobalVars.socketIO = socketIOInstance;
// Add to global, so the controllers can manage own actions like create, join ...
httpServer.listen(port, () => {
console.log(`Server Listening on the port ${port}`);
})
...
当我从客户端访问时,我可以看到
SOCKET.IO A USER CONNECTED
和 Hi
在浏览器控制台中。其次,在 api Controller 中。
let GlobalVars = require('../state/GlobalVars');
...
router.post('/create', (req, res) => {
console.log('GenerateGameSokect');
let game = new Game();
let gameId = game.gameId;
// console.log('Global vars ', GlobalVars.socketIO);
GlobalVars.socketIO.emit('create', {
room: gameId
});
res.json({
result : 'SUCCESS',
game : game
})
});
我进口了
GlobalVars
其中包含 socketIO 实例。所以我所期望的是,socket create
由语句 GlobalVars.socketIO.emit('create', Object)
触发的事件但在服务器日志中找不到消息。我不知道我错过了什么。
我追求的最终形式是……
感谢您阅读我的问题 B. Here is full source code till now(bitbucket public)
================== 编辑====================
我明白了(也许......)
我想要的用户流程是......
socket.io
但是,创建
socket.io
服务器中的连接对我来说看起来很奇怪,解决方案取决于客户端。新的用户流程我会改变
================== 编辑#2 ====================
这是一种结论。看来我只是误解了套接字通信的概念。喜欢回答和回复说,
Socket
和 HTTP
是完全不同的 channel ,没有办法将两者联系起来。 (至少,没有打开从 http 服务器到套接字的新连接)如有错误,请补充,谢谢
最佳答案
现在我明白你了。或者至少我认为!
让我们这样说:套接字上有两个(不对称的)边,服务器和客户端。在我对你的帖子的评论中,我分别称之为“全局经理”和“套接字”。
const server = require('socket.io')(yourHttpServer);
// client is installed as well when `npm i socket.io`
const client = require('socket.io-client')('http://localhost:' + yourServerPort);
// `socket` is the server side of the socket
server.on('connection', (socket) => {
// this will be triggered by client sides emitting 'create'
socket.on('create', (data) => {
console.log('a client socket just fired a "create" event!');
});
});
// this will be triggered by server side emitting 'create'
client.on('create', (data) => {
server.emit('create', {content: 'this will result in an infinite loop of "create" events!'});
});
在您的
/create
路线,当你 GlobalVars.socketIO.emit('create', ...)
,服务器端套接字处理程序不会被触发,但是如果您有通过浏览器连接的客户端(或者,如我上面所示,如果您直接从服务器连接客户端套接字),那么这些将触发它们的 'create'
听众,如果有的话。希望这可以帮助您走上正确的轨道!
关于node.js - 从服务器 `socket.io` 触发 (`node.js` 事件),而不是从客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54511685/