-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
121 lines (104 loc) · 2.63 KB
/
service.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
package gate
import (
"encoding/binary"
"github.com/yddeng/smux"
"github.com/yddeng/utils/log"
"io"
"net"
"sync"
"time"
)
/*
service 第一次连接,不指定ID,由gate分配。
重连后附带ID,在gate上重建对象。
用途是: 网络闪断,希望连接到上次登录的服务器。并且上次登录的服务器还没有执行下线流程,仍保留用户信息
*/
type Service struct {
id uint32
token string
muxSession *smux.MuxSession
channels map[uint16]*channel
chanLock sync.Mutex
}
func (this *Service) Accept() (*smux.MuxConn, error) {
return this.muxSession.Accept()
}
func (this *Service) Close() {
this.muxSession.Close()
}
func serviceLogin(conn net.Conn, id uint32, token string) (uint32, error) {
data := make([]byte, 9)
data[0] = typeServer
binary.BigEndian.PutUint32(data[1:], id)
binary.BigEndian.PutUint32(data[5:], HashNumber(token))
conn.SetWriteDeadline(time.Now().Add(time.Second * 2))
if _, err := conn.Write(data); err != nil {
panic(err)
}
conn.SetWriteDeadline(time.Time{})
ret := make([]byte, 8)
conn.SetReadDeadline(time.Now().Add(time.Second * 2))
if _, err := io.ReadFull(conn, ret); err != nil {
return 0, err
}
conn.SetReadDeadline(time.Time{})
code := binary.BigEndian.Uint32(ret)
if code != OK {
return 0, GetCode(code)
}
id = binary.BigEndian.Uint32(data[4:])
return id, nil
}
func newService(conn net.Conn, id uint32, token string) *Service {
return &Service{
id: id,
token: token,
muxSession: smux.NewMuxSession(conn),
channels: map[uint16]*channel{},
}
}
func NewService(conn net.Conn, id uint32, token string) (*Service, error) {
if id, err := serviceLogin(conn, id, token); err != nil {
return nil, err
} else {
return newService(conn, id, token), nil
}
}
func DialService(addr string, id uint32, token string) (*Service, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
return NewService(conn, id, token)
}
func (this *Service) accept(closef func(err error)) {
for {
muxConn, err := this.muxSession.Accept()
if err != nil {
closef(err)
this.muxSession.Close()
return
}
// 暂不允许对端开启
muxConn.Close()
}
}
func (this *Service) handleConn(conn net.Conn) error {
muxConn, err := this.muxSession.Open()
if err != nil {
return err
}
id := muxConn.ID()
ch := newChannel(muxConn, conn)
log.Info("new channel", muxConn.ID())
this.chanLock.Lock()
this.channels[id] = ch
this.chanLock.Unlock()
ch.run(func(err error) {
log.Errorf("channel %d closed %v", id, err)
this.chanLock.Lock()
delete(this.channels, id)
this.chanLock.Unlock()
})
return nil
}