/
server.go
102 lines (83 loc) · 1.91 KB
/
server.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"fmt"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
. "github.com/ecofast/rtl/netutils"
"github.com/ecofast/tcpsock"
. "github.com/ecofast/tcpsock/samples/chatroom/protocol"
)
var (
shutdown = make(chan bool, 1)
mutex sync.Mutex
clients map[uint32]*tcpsock.TcpConn
)
func init() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-signals
shutdown <- true
}()
}
func main() {
clients = make(map[uint32]*tcpsock.TcpConn)
server := tcpsock.NewTcpServer(9999, 5, onConnConnect, onConnClose, onProtocol)
log.Println("=====service start=====")
go server.Serve()
ticker := time.NewTicker(2 * time.Minute)
go func() {
for range ticker.C {
//log.Printf("num of conn: %d\n", server.NumOfConn())
// broadcast()
}
}()
<-shutdown
log.Println("server shutdown...")
server.Close()
log.Println("=====service end=====")
}
func onConnConnect(conn *tcpsock.TcpConn) {
conn.Write(genChatPacket("master01", fmt.Sprintf("Welcome! Your IP is %s", IPFromNetAddr(conn.RawConn().RemoteAddr()))))
mutex.Lock()
defer mutex.Unlock()
clients[conn.ID()] = conn
}
func onConnClose(conn *tcpsock.TcpConn) {
mutex.Lock()
defer mutex.Unlock()
delete(clients, conn.ID())
}
func onMsg(conn *tcpsock.TcpConn, p *ChatPacket) {
fmt.Println(p)
mutex.Lock()
defer mutex.Unlock()
for _, c := range clients {
c.Write(p)
}
}
func onProtocol() tcpsock.Protocol {
proto := &ChatProtocol{}
proto.OnMessage(onMsg)
return proto
}
func genChatPacket(userName, words string) *ChatPacket {
var head PacketHead
head.Signature = ChatSignature
copy(head.UserName[:], ([]byte(userName[:]))[:])
body := []byte(words)
head.BodyLen = uint32(len(body))
return NewChatPacket(head, body)
}
func broadcast() {
mutex.Lock()
defer mutex.Unlock()
packet := genChatPacket("master01", "broadcast test")
for _, c := range clients {
c.Write(packet)
}
}