实时推送通知 Golang

huangapple go评论107阅读模式
英文:

Realtime push notification golang

问题

我想在我的Web应用程序中实现实时通知功能。我正在按照这个示例"https://github.com/gorilla/websocket/tree/master/examples/chat"进行操作。我需要服务器(hub)接收消息,并根据某种ID将这些消息推送给各个客户端。我该如何做到这一点?

英文:

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

得分: 1

从你提到的示例中:

	case message := <-h.broadcast:
		for client := range h.clients {
			select {
			case client.send <- message:
			default:
				close(client.send)
				delete(h.clients, 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)
				}
			}
		}
	}

这应该给你一个思路。其余的部分由你来完成。

注意:我的示例代码可以通过使用map[clientID]Client来直接访问客户端来进行优化。

英文:

From the sample you mentioned:

	case message := &lt;-h.broadcast:
		for client := range h.clients {
			select {
			case client.send &lt;- 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 := &lt;-h.clientMessage:
		for client := range h.clients {
            if message.ClientID == client.ID {
				select {
				case client.send &lt;- 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.

huangapple
  • 本文由 发表于 2017年8月16日 04:24:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/45700976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定