Exemplo n.º 1
0
func (h *hub) run() {
	log.Info("hub run")
	for {
		// log.Info("hub for")
		// h.broadcast <- string("salut")
		select {
		case c := <-h.register:
			log.Info("register")
			h.clients[c] = true
			c.send <- []byte(h.content)
			break
		case c := <-h.unregister:
			log.Info("unregister")
			_, ok := h.clients[c]
			if ok {
				delete(h.clients, c)
				close(c.send)
			}
			break
		case m := <-h.broadcast:
			h.content = m
			h.broadcastMessage()
			break
		default:
		}
	}
}
Exemplo n.º 2
0
func handleWebsocket(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.WithField("err", err).Println("Upgrading to websockets")
		http.Error(w, "Error Upgrading to websockets", 400)
		return
	}
	log.Info("NEW CONNECTION")

	c := &client{
		send: make(chan []byte, maxMessageSize),
		ws:   ws,
		id:   h.id,
	}
	h.id += 1
	h.register <- c
	go handleMessage(c)

}
Exemplo n.º 3
0
func closeConnection(c *client) {
	log.Info("CLOSE CONNECTION", c.id)
	c.ws.WriteMessage(websocket.CloseMessage, []byte{})
	h.unregister <- c
	delete(h.messages, strconv.Itoa(c.id))
}