-
Notifications
You must be signed in to change notification settings - Fork 11
/
message.go
73 lines (62 loc) · 1.38 KB
/
message.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
package main
import (
"encoding/json"
"fmt"
"io"
"net"
"sync"
"x-tiktok/controller"
)
var chatConnMap = sync.Map{}
func RunMessageServer() {
listen, err := net.Listen("tcp", "127.0.0.1:9090")
if err != nil {
fmt.Printf("Run message sever failed: %v\n", err)
return
}
for {
conn, err := listen.Accept()
if err != nil {
fmt.Printf("Accept conn failed: %v\n", err)
continue
}
go process(conn)
}
}
func process(conn net.Conn) {
defer conn.Close()
var buf [256]byte
for {
n, err := conn.Read(buf[:])
if n == 0 {
if err == io.EOF {
break
}
fmt.Printf("Read message failed: %v\n", err)
continue
}
var event = controller.MessageSendEvent{}
_ = json.Unmarshal(buf[:n], &event)
fmt.Printf("Receive Message:%+v\n", event)
fromChatKey := fmt.Sprintf("%d_%d", event.UserId, event.ToUserId)
if len(event.MsgContent) == 0 {
chatConnMap.Store(fromChatKey, conn)
continue
}
toChatKey := fmt.Sprintf("%d_%d", event.ToUserId, event.UserId)
writeConn, exist := chatConnMap.Load(toChatKey)
if !exist {
fmt.Printf("User %d offline\n", event.ToUserId)
continue
}
pushEvent := controller.MessagePushEvent{
FromUserId: event.UserId,
MsgContent: event.MsgContent,
}
pushData, _ := json.Marshal(pushEvent)
_, err = writeConn.(net.Conn).Write(pushData)
if err != nil {
fmt.Printf("Push message failed: %v\n", err)
}
}
}