简体   繁体   English

如何处理来自 socket.io 房间“发射”事件的多个写入函数?

[英]How do I handle multiple write functions from a socket.io room `emit` event?

Going to provide some context first.首先要提供一些上下文。 Question is at the bottom.问题在底部。

Background背景

I'm making a browser based javascript game where users join a room and move tiles around.我正在制作一个基于浏览器的 javascript 游戏,用户可以在其中加入房间并四处移动瓷砖。 When the game is over, user data is sent to the server, where it needs to be merged with other user data, and then the resulting data gets sent back to each user to display the results of other players.游戏结束后,用户数据被发送到服务器,需要与其他用户数据合并,然后将结果数据发送回每个用户,以显示其他玩家的结果。

I am using an Express node server with socket.io (front end is react, fwiw)我正在使用带有 socket.io 的 Express 节点服务器(前端是反应,fwiw)

The issue at hand手头的问题

I have a json file for a game room, lets call it 1a2b.json :我有一个游戏室的 json 文件,我们称之为1a2b.json

{
  "roomID":"1a2b",
  "users":[
    {
      "name":"username",
      "id": 123,
      "tiles":[
        {"char":"I","x":false,"y":false,"r":false,"id":"1"},
        {"char":"X","x":false,"y":false,"r":false,"id":"2"}
      ]
    }
    {
      "name":"username2",
      "id": 456,
      "tiles":[
        {"char":"V","x":false,"y":false,"r":false,"id":"3"},
        {"char":"K","x":false,"y":false,"r":false,"id":"4"}
      ]
    }
  ]
}

When a game ends, players emit a socket event ( game-end ) that sends updated player tiles data.当游戏结束时,玩家会发出一个套接字事件 ( game-end ),该事件会发送更新的玩家tiles数据。 Something like:就像是:

{
  "name":"username",
  "id": 123,
  "roomID":"1a2b",
  "tiles":[
    {"char":"I","x":21,"y":30,"r":"45deg","id":"1"},
    {"char":"X","x":50,"y":80,"r":false,"id":"2"}
  ]
}

On the server, when the game-end socket event is observed, I need to update the original 1a2b.json file with the new data from each user, replacing the old tiles data for a player with the new tiles data.在服务器上,当观察到game-end套接字事件时,我需要使用来自每个用户的新数据更新原始1a2b.json文件,用新的tiles tiles

All users will be emitting the event at the same time, which I assume will cause an fs.writefile error for some users.所有用户将同时发出事件,我认为这会导致某些用户出现fs.writefile错误。

The Question问题

How do I handle updating and writing the contents of 1a2b.json when multiple update/write events are happening at the same time to the same file?当多个更新/写入事件同时发生到同一个文件时,如何处理更新和写入1a2b.json的内容? And within a proposed solution, is there a way to tell when all write requests are complete, so I can emit data from the completed json file back to users?在提出的解决方案中,是否有办法判断所有写入请求何时完成,以便我可以将完成的 json 文件中的数据发回给用户?

If you're just running one Express instance, since Node is single-threaded, the server will only be able to process one write at a time anyway.如果你只运行一个 Express 实例,因为 Node 是单线程的,服务器一次只能处理一个写入。 So you will not encounter any errors.所以你不会遇到任何错误。

The real solution would be to write to a database rather than a file.真正的解决方案是写入数据库而不是文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM