首页 > 解决方案 > 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.

标签: javascriptnode.jsrestwebsocketkoa

解决方案


你不能把它发射到同一个套接字吗?

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
  });

推荐阅读