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 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器