示例#1
0
文件: handlers.go 项目: kitech/micro
func (c *conn) writeLoop() {
	ticker := time.NewTicker(pingTime)

	subscriber, err := broker.Subscribe(c.topic, func(p broker.Publication) error {
		b, err := json.Marshal(p.Message())
		if err != nil {
			return nil
		}
		return c.write(websocket.TextMessage, b)
	})

	defer func() {
		subscriber.Unsubscribe()
		ticker.Stop()
		c.ws.Close()
	}()

	if err != nil {
		log.Error(err.Error())
		return
	}

	for _ = range ticker.C {
		if err := c.write(websocket.PingMessage, []byte{}); err != nil {
			return
		}
	}
}
示例#2
0
func sub() {
	_, err := broker.Subscribe(topic, func(p broker.Publication) error {
		fmt.Println("[sub] received message:", string(p.Message().Body), "header", p.Message().Header)
		return nil
	})
	if err != nil {
		fmt.Println(err)
	}
}