duadlkc5762218 2018-12-16 22:05
浏览 622
已采纳

Golang超时或提早返回

I'm attempting to build a realtime multiplayer game server in Golang using websockets as a learning project, and I'm having difficulty understanding how exactly I'm supposed to implement this concept:

All of the users in a game room are given a duration, MAX_TIMEOUT to respond to a prompt provided. Responses are submitted via websocket connections. If all of the users respond before MAX_TIMEOUT, then Action A should happen, using the responses. If MAX_TIMEOUT elapses before all of the prompts are submitted, then Action B should happen, using the responses available.

Coming from Node.JS, I could see myself implementing this with Promises, but in Golang, I'm rather lost.

Any advice?

  • 写回答

2条回答 默认 最新

  • dongpiao1983 2018-12-16 23:06
    关注

    Checkout gorilla/websocket's chat example. It uses tickers and channels in client.go like mentioned above.

    The server's prompt handling could be its own routine running parallel to the read/write pump routines.

    go func() {
        for {
            for _, player := range players {
                player.Answered = false
                player.Send("prompt")
            }
    
            time.Sleep(time.Second * 10)
    
            for _, player := range players {
                if player.Answered {
                   player.Send("You answered")
                } else {
                   player.Send("Too slow")
                }
            }
        }
    }()
    
    // the reading routine sets `Answered` true when message received
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?