doqpm82240 2017-08-15 20:24
浏览 363

实时推送通知golang

I want to implement a real time notification feature in my web application. I am following this example "https://github.com/gorilla/websocket/tree/master/examples/chat". I need the server (hub) to get messages, it needs to push those messages to individual clients based on some form of ID. how can I do this?

  • 写回答

1条回答 默认 最新

  • donglv9116 2017-08-16 08:42
    关注

    From the sample you mentioned:

        case message := <-h.broadcast:
            for client := range h.clients {
                select {
                case client.send <- message:
                default:
                    close(client.send)
                    delete(h.clients, client)
                }
            }
        }
    

    This is the case where a message is broadcasted to all clients. As you can see it loops over all registered clients and sends the message to every single one of them.

    To preserve this functionality we will simply add another case: send to a single client.

        case message := <-h.clientMessage:
            for client := range h.clients {
                if message.ClientID == client.ID {
                    select {
                    case client.send <- message:
                    default:
                        close(client.send)
                        delete(h.clients, client)
                    }
                }
            }
        }
    

    This should give you an idea. The rest I leave up to you.

    Note: my sample code can be optimised by e.g. using a map[clientID]Client to access the client directly.

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)