-
Notifications
You must be signed in to change notification settings - Fork 0
/
webSocket.go
76 lines (43 loc) · 993 Bytes
/
webSocket.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
package main
import(
"log"
"net/http"
"github.com/myselfBZ/Chat/models"
)
func HandleConn(w http.ResponseWriter, r *http.Request){
username := r.Context().Value("username").(string)
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil{
log.Fatal("error upgrading the Conn:", err)
}
client := Client{
Username: username,
Conn: conn,
}
Conns[client] = true
defer conn.Close()
for{
var msg models.Message
err := conn.ReadJSON(&msg)
if err != nil {
delete(Conns, client)
break
}
broadcast <- msg
}
}
func HandleMesg(){
for{
msg := <- broadcast
for client := range Conns{
if client.Username == msg.Reciever{
err := client.Conn.WriteJSON(msg)
if err != nil{
log.Fatal("error writing json:", err)
client.Conn.Close()
delete(Conns, client)
}
}
}
}
}