-
Notifications
You must be signed in to change notification settings - Fork 508
/
server.go
75 lines (65 loc) · 1.74 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
package main
import (
"context"
"encoding/binary"
"fmt"
"time"
"github.com/TarsCloud/TarsGo/tars/transport"
)
// MyServer testing tars udp server
type MyServer struct{}
func (s *MyServer) GetCloseMsg() []byte {
return []byte("")
}
func (s *MyServer) DoClose(ctx context.Context) {
}
// Invoke recv package and make response.
func (s *MyServer) Invoke(ctx context.Context, req []byte) (rsp []byte) {
rsp = make([]byte, 4)
rsp = append(rsp, []byte("Hello ")...)
rsp = append(rsp, req[4:]...)
binary.BigEndian.PutUint32(rsp[:4], uint32(len(rsp)))
return
}
// ParsePackage parse full tars package.
func (s *MyServer) ParsePackage(buff []byte) (pkgLen, status int) {
if len(buff) < 4 {
return 0, transport.PackageLess
}
length := binary.BigEndian.Uint32(buff[:4])
if length > 1048576000 || len(buff) > 1048576000 { // 1000MB
return 0, transport.PackageError
}
if len(buff) < int(length) {
return 0, transport.PackageLess
}
return int(length), transport.PackageFull
}
// InvokeTimeout show how to deal with timeout response.
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: "udp",
Address: "127.0.0.1:3333",
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)
if err := svr.Listen(); err != nil {
panic(err)
}
if err := svr.Serve(); err != nil {
fmt.Println(err)
}
}