-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (65 loc) · 1.36 KB
/
main.go
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"fmt"
"github.com/gorilla/websocket"
"log"
"net/http"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type Client struct {
conn *websocket.Conn
username string
}
var clients = make(map[*websocket.Conn]Client)
func wsEndpoint(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
username := r.URL.Query().Get("username")
client := Client{conn: conn, username: username}
clients[conn] = client
log.Println("client", username, "connected")
if err := conn.WriteMessage(1, []byte("Hi "+username+"!")); err != nil {
log.Println(err)
delete(clients, conn)
conn.Close()
return
}
go reader(client)
}
func reader(client Client) {
conn := client.conn
username := client.username
defer func() {
conn.Close()
delete(clients, conn)
}()
for {
messageType, message, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
fmt.Println(username+":", string(message))
for _, c := range clients {
if c.conn != conn {
if err := c.conn.WriteMessage(messageType, []byte(username+": "+string(message))); err != nil {
log.Println(err)
return
}
}
}
}
}
func setUpRoutes() {
http.HandleFunc("/ws", wsEndpoint)
}
func main() {
setUpRoutes()
http.ListenAndServe(":9999", nil)
}