forked from TarsCloud/TarsGo
/
server.go
67 lines (59 loc) · 1.62 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
package main
import (
"encoding/binary"
"fmt"
"time"
"github.com/TarsCloud/TarsGo/tars/transport"
)
//MyServer struct for testing tars tcp server
type MyServer struct{}
//Invoke recv request and make response.
func (s *MyServer) Invoke(req []byte) (rsp []byte) {
fmt.Println("recv", string(req))
rsp = make([]byte, 4)
rsp = append(rsp, []byte("Hello ")...)
rsp = append(rsp, req...)
binary.BigEndian.PutUint32(rsp[:4], uint32(len(rsp)))
return
}
//ParsePackage parse package from buff,check if tars package finished.
func (s *MyServer) ParsePackage(buff []byte) (pkgLen, status int) {
if len(buff) < 4 {
return 0, transport.PACKAGE_LESS
}
length := binary.BigEndian.Uint32(buff[:4])
if length > 1048576000 || len(buff) > 1048576000 { // 1000MB
return 0, transport.PACKAGE_ERROR
}
if len(buff) < int(length) {
return 0, transport.PACKAGE_LESS
}
return int(length), transport.PACKAGE_FULL
}
//InvokeTimeout how to detail with timeout package.
func (s *MyServer) InvokeTimeout(pkg []byte) []byte {
payload := []byte("timeout")
ret := make([]byte, 4+len(payload))
binary.BigEndian.PutUint32(pkg[:4], uint32(len(ret)))
copy(pkg[4:], payload)
return ret
}
func main() {
conf := &transport.TarsServerConf{
Proto: "tcp",
Address: "localhost:3333",
//MaxAccept: 500,
MaxInvoke: 20,
AcceptTimeout: time.Millisecond * 500,
ReadTimeout: time.Millisecond * 100,
WriteTimeout: time.Millisecond * 100,
HandleTimeout: time.Millisecond * 6000,
IdleTimeout: time.Millisecond * 600000,
}
s := MyServer{}
svr := transport.NewTarsServer(&s, conf)
err := svr.Serve()
if err != nil {
panic(err)
}
}