-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.go
64 lines (53 loc) · 1.29 KB
/
socket.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
package main
import (
"encoding/json"
"log"
"github.com/gorilla/websocket"
)
func listen(conn *websocket.Conn) {
for {
messageType, messageContent, err := conn.ReadMessage()
if err != nil {
if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
removeClient(conn)
}
log.Println(err)
return
}
var content Input
err = json.Unmarshal(messageContent, &content)
if err != nil {
log.Println("Error unmarshalling message:", err)
continue
}
if err := db.Create(&content).Error; err != nil {
log.Println("database error:", err)
return
}
// Check if the receiver exists in the clientsMap
receiverConn, exists := clientsMap[content.Target]
if !exists {
log.Println("Receiver not found:", content.Target)
continue
}
messageJSON, err := json.Marshal(content)
if err != nil {
log.Println("Error marshaling message:", err)
return
}
// Send the message to the receiver
err = receiverConn.WriteMessage(messageType, messageJSON)
if err != nil {
log.Println("Error sending message to receiver:", err)
}
}
}
func removeClient(client *websocket.Conn) {
// Remove the client from the clients map
for username, conn := range clientsMap {
if conn == client {
delete(clientsMap, username)
return
}
}
}