javascript - How I can use a WebSocket connection with Socket.io events and a Koa rest api?
问题描述
I'm making a multiplayer game that is using websockets to share the gamestate between all the connected players.
I decided to use socket.io with koa and now I'm facing the following problem.
First when a user connects to the server a new player is created.
const playersMeta = {}
io.on('connect', socket => {
const playerId = uniqid() // Creates a new unique id for a player
playersMeta[socket.id] = { playerId } // Stores the players id using the socket.id as key
socket.on('disconnect', () => {
delete playersMeta[playerId]
})
})
The thing is that a player needs to know the unique id that the server assigned to it. The reason is that there is a game state that tells every connected player where all the entities are. The camera follows the player that was created when you enter the game, that's why I need to know which player the camera should follow.
I can create a new socket.io event, an then the player emits an event that returns the id that you want but it looks like is getting too much complicated.
Events are nice to sync between different clients, in real time, data that need too change but I'm sure that the id of the player is not going to change.
Maybe is better to just create an api rest endpoint to get this data. I'm using Koa and I'm not sure if I can use the same websocket connection instead of using http.
解决方案
你不能把它发射到同一个套接字吗?
const playersMeta = {}
io.on('connect', socket => {
const playerId = uniqid() // Creates a new unique id for a player
playersMeta[socket.id] = { playerId } // Stores the players id using the socket.id as key
socket.emit('connected', { serverId: 'foo'});
socket.on('disconnect', () => {
delete playersMeta[playerId]
})
});
在您的客户端上:
var socket = io('http://server');
socket.on('connected', function (data) {
console.log(data); // { serverId: 'foo'}
// do whatever you want with the servid
});
推荐阅读
- c# - 我可以在 C# 中链接多个“或”(||) 运算符吗?
- javascript - 如何在 javascript 中正确使用 DOM 样式的边距顶部属性?
- powerbi - 有没有办法在powerbi的报告页面上轻松计算表格中的行数?
- html - Angular 材料目录的 HTML 代码
- javascript - 如何将特定索引的数组分配给另一个嵌套数组?
- python - 导入 firestore 时没有名为“google.api_core.client_options”的模块
- python-3.x - 带有 statsmodels 的 sm.OLS.from_formula('variable1 ~ variable2 + x ') 问题
- haskell - 为什么 GHC 不导入 Semigroup ((<>))
- arrays - 用于直方图的 JavaScript 中的分箱数组
- botframework - “机器人无效。错误:MsaAppId:MsaAppId 已在使用中