package main import log net http github com gorilla websocket var upgr

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
var clients = make(map[*websocket.Conn]bool) // connected clients
var broadcast = make(chan string) // broadcast channel
func handleMessages() {
for {
// Grab the next message from the broadcast channel
msg := <-broadcast
// Send it out to every client that is currently connected
for client := range clients {
err := client.WriteJSON(msg)
if err != nil {
log.Printf("error: %v", err)
client.Close()
delete(clients, client)
}
}
}
}
func handler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
// defer client remove
clients[conn] = true
for {
_, msg, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
broadcast <- string(msg)
}
}
func main() {
http.HandleFunc("/ws", handler)
go handleMessages()
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}