donglianglu8136 2015-12-21 15:19
浏览 74
已采纳

防止双重执行PHP + JS

I am using PHP + JS to create a game. Every game is person vs person, so only 2 users. It works, but I have trouble with "double bookings". Like this:

  1. User1 creates Game #10 (PHP)
  2. Game shows up in the lobby (JS)
  3. User2 joins Game #10 (PHP)
  4. User3 joins Game #10 (PHP)
  5. Game disappears from lobby (JS)

The steps 3 and 4 happen with only milliseconds between. When a user joins a game, I first check if the "seat" is taken. If not - i parse all essential data, etc, and then i set the seat as taken. During the parsing, it seems as users can join the same game. This is a matter of milliseconds, as I stated earlier. But how do i prevent this?

  • 写回答

1条回答 默认 最新

  • doujiu3768 2015-12-21 15:37
    关注

    You could make use of an implicit database record lock, by performing a kind of test-and-set operation for taking a free seat, something like this:

    UPDATE blackjack_hands
    SET    user_id = :user_id
    WHERE  user_id IS NULL
    AND    blackjack_id = :blackjack_id
    AND    creator = '0';
    

    Then check the number of updated records (for instance with msqli_affected_rows) after that to decide if the seat was successfully taken (which implies it was free).

    That way it will not be possible for a second user to make the same successful update.

    This would be an example of pessimistic locking.

    The above query assumes that during game creation, you would insert two records immediately, one for the creator's user_id (as you certainly do already), and one for the unknown opponent's user_id, initialised as NULL.

    NB: Consider moving away from the deprecated mysql_* functions. You could use the mysqli_* or PDO interface instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件