示例#1
0
func main() {
	c = nconfig.Load()
	qAddr := c.GetString(nconfig.KEY_QUEUE_ADDR)
	n, e := nats.Connect(qAddr)

	if e != nil {
		panic(e)
	}

	conn, err := nats.NewEncodedConn(n, nats.JSON_ENCODER)
	if err != nil {
		panic(err)
	}

	conn.Subscribe("realtime-jobs", jobsHandler)
	log.Info("Connected to NATS on " + qAddr)

	http.HandleFunc("/register", func(w http.ResponseWriter, r *http.Request) {
		conn, err := upgrader.Upgrade(w, r, nil)

		if err != nil {
			panic(err)
			return
		}

		connections = append(connections, conn)
	})

	port := c.GetString(nconfig.KEY_BROKER_PORT)
	log.Info("Starting WS service on port " + port)
	http.ListenAndServe(port, nil)
}
示例#2
0
func jobsHandler(m *nats.Msg) {
	log.Info("Got message " + string(m.Data))

	for i, c := range connections {
		log.Info("Sending message to connection: " + strconv.Itoa(i+1))
		c.WriteMessage(websocket.TextMessage, m.Data)
	}
}
示例#3
0
func main() {
	c := nconfig.Load()

	server.Initialize(c)

	port := c.GetString(nconfig.KEY_REALTIME_PORT)
	log.Info("Listening on port: " + port)
	log.Info(http.ListenAndServe(port, nil))
}
示例#4
0
func (p *messageProcessor) Process(mType int, m []byte) error {
	if mType != MESSAGE_TYPE_STRING {
		return errors.New("Unsupported message type: " + strconv.Itoa(mType))
	}

	//TODO:
	log.Info(string(m))

	return nil
}
示例#5
0
func Initialize(c *viper.Viper) {
	config = c

	http.HandleFunc("/data", func(w http.ResponseWriter, r *http.Request) {
		conn, err := upgrader.Upgrade(w, r, nil)

		if err != nil {
			panic(err)
			return
		}

		//TODO: token authentication
		token := r.URL.Query().Get("token") //the hash is a unique, per user
		realtimeConn := NewConnection(conn, token)

		GetConnectionStore().Put(token, realtimeConn)
	})

	wsDialer := websocket.Dialer{}
	conn, _, err := wsDialer.Dial(c.GetString(nconfig.KEY_BROKER_HOST)+c.GetString(nconfig.KEY_BROKER_PORT)+"/register", nil)
	if err != nil {
		panic(err)
	}

	go func() {
		defer conn.Close()
		for {
			_, message, err := conn.ReadMessage()
			if err != nil {
				log.Info("read: ", err)
				break
			}

			log.Info("recv: %s", message)
		}
	}()
}
示例#6
0
func Notify(data models.JSON) {
	subj := c.GetString(nconfig.CONST_REALTIME_JOBS_SUBJ)
	log.Info("Publishing to queue subject: " + subj + " data: " + data.String())
	qConn.Publish(subj, data)
}