예제 #1
0
// Listen on different channels and act accordingly
func (broker *Broker) listen() {
	for {
		select {
		case s := <-broker.newClients:

			// A new client has connected.
			// Register their message channel
			broker.clients[s] = true
			log.Printf("Client added. %d registered clients", len(broker.clients))
		case s := <-broker.closingClients:

			// A client has dettached and we want to
			// stop sending them messages.
			delete(broker.clients, s)
			log.Printf("Removed client. %d registered clients", len(broker.clients))
		case event := <-broker.Notifier:

			// We got a new event from the outside!
			// Send event to all connected clients
			json, err := data.EncodeJSON(event)
			if err != nil {
				log.Println("Error encoding event to JSON")
			} else {
				for clientMessageChan, _ := range broker.clients {
					clientMessageChan <- json
				}
			}
		}
	}

}
예제 #2
0
func encodeEventIntoString(event *data.Event) (str string, err error) {
	bytes, err := data.EncodeJSON(event)
	if err != nil {
		return
	}
	return string(bytes), err
}