-
Notifications
You must be signed in to change notification settings - Fork 60
/
service_test.go
68 lines (54 loc) · 1.18 KB
/
service_test.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
package zero
import (
"fmt"
"net"
"testing"
"time"
)
func TestService(t *testing.T) {
host := "127.0.0.1:18787"
ss, err := NewSocketService(host)
if err != nil {
return
}
// ss.SetHeartBeat(5*time.Second, 30*time.Second)
ss.RegMessageHandler(HandleMessage)
ss.RegConnectHandler(HandleConnect)
ss.RegDisconnectHandler(HandleDisconnect)
go NewClientConnect()
timer := time.NewTimer(time.Second * 1)
go func() {
<-timer.C
ss.Stop("stop service")
t.Log("service stoped")
}()
t.Log("service running on " + host)
ss.Serv()
}
func HandleMessage(s *Session, msg *Message) {
fmt.Println("receive msgID:", msg)
fmt.Println("receive data:", string(msg.GetData()))
}
func HandleDisconnect(s *Session, err error) {
fmt.Println(s.GetConn().GetName() + " lost.")
}
func HandleConnect(s *Session) {
fmt.Println(s.GetConn().GetName() + " connected.")
}
func NewClientConnect() {
host := "127.0.0.1:18787"
tcpAddr, err := net.ResolveTCPAddr("tcp", host)
if err != nil {
return
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
return
}
msg := NewMessage(1, []byte("Hello Zero!"))
data, err := Encode(msg)
if err != nil {
return
}
conn.Write(data)
}