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 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办