-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
135 lines (120 loc) · 2.37 KB
/
server_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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package main
import (
"encoding/json"
"log"
"net"
"os"
"testing"
"github.com/nightlegend/hi/core"
)
const (
// LoginRequest login request flag
LoginRequest = 0x0001
// LoginRequest login success flag
LoginSuccess = 0x0010
// LoginFailed login failed flag
LoginFailed = 0x0100
UserMessageRequest = 0x0002
UserMessageSuccess = 0x0020
UserMessageFail = 0x00200
)
// ChatMessage is define trans message struct
type ChatMessage struct {
ID string
ChatType string
FromID string
TOID string
GroupName string
MessageType string
Message []byte
UserList []UserInfo
}
// UserInfo user information type
type Header struct {
HandlerID int
CommandID int
}
type TCPRequest struct {
Hd Header
Body []byte
}
// TCPResponse a tcp response struct
type TCPResponse struct {
HD Header
Body []byte
}
type UserInfo struct {
ID string
Name string
Password string
Message string
}
var userInfo UserInfo
func TestMain(t *testing.T) {
go core.SocketServer()
tcpAddr, err := net.ResolveTCPAddr("tcp4", "localhost:9090")
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
t.Fatal(err)
} else {
t.Log("socket server normally..")
}
go sendMsg(conn)
buff := make([]byte, 1024)
for {
length, err := conn.Read(buff)
if err != nil {
conn.Close()
t.Log("Server crashed..bye")
os.Exit(0)
}
t.Log(string(buff[0:length]))
go handler(conn, buff[0:length], t)
}
}
// sendMsg send message to server.
func sendMsg(conn net.Conn) {
var user UserInfo
var tcpReq TCPRequest
var header Header
var data []byte
user = UserInfo{
ID: "",
Name: "David Guo",
Password: "12345",
Message: "Hi ,你好",
}
body, _ := json.Marshal(user)
header = Header{
HandlerID: 0x0001,
CommandID: LoginRequest,
}
tcpReq = TCPRequest{
Hd: header,
Body: body,
}
data, _ = json.Marshal(tcpReq)
length, err := conn.Write(data)
log.Println(length)
if err != nil {
log.Println(err.Error())
conn.Close()
os.Exit(0)
}
}
// handler handle response.
func handler(conn net.Conn, data []byte, t *testing.T) {
var resp TCPResponse
var chatMessage ChatMessage
json.Unmarshal(data, &resp)
switch resp.HD.HandlerID {
case 0x0001:
json.Unmarshal(resp.Body, &userInfo)
t.Log(userInfo.ID)
os.Exit(0)
case 0x0002:
json.Unmarshal(resp.Body, &chatMessage)
t.Log(string(chatMessage.Message))
os.Exit(0)
}
}