forked from hongcha98/go-dap
-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn.go
96 lines (88 loc) · 1.84 KB
/
conn.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
package dap
import (
"bufio"
"encoding/json"
"errors"
"io"
"sync/atomic"
)
type Conn struct {
io io.ReadWriteCloser
handler Handler
seq int64
awaitMap map[int]chan []byte
}
func NewConn(io io.ReadWriteCloser, handler Handler) *Conn {
conn := &Conn{
io: io,
handler: handler,
seq: 0,
awaitMap: make(map[int]chan []byte),
}
return conn
}
type Handler interface {
Handle(*Conn, Message)
}
// 阻塞等待结果
func (conn *Conn) SendRequest(request RequestMessage, response ResponseMessage) error {
oldSeq := request.GetSeq()
request.GetRequest().Seq = int(atomic.AddInt64(&conn.seq, 1))
await := make(chan []byte, 1)
conn.awaitMap[request.GetSeq()] = await
defer func() {
request.GetRequest().Seq = oldSeq
}()
if err := conn.Send(request); err != nil {
return err
}
message := <-await
if message == nil {
return errors.New("conn close")
}
err := json.Unmarshal(message, response)
if err == nil {
response.GetResponse().RequestSeq = oldSeq
}
return err
}
// 非阻塞,不会拿到结果
func (conn *Conn) Send(message Message) error {
return WriteProtocolMessage(conn.io, message)
}
func (conn *Conn) Run() {
reader := bufio.NewReader(conn.io)
for {
content, err := ReadBaseMessage(reader)
if err != nil {
break
}
message, err := DecodeProtocolMessage(content)
if err != nil {
// TODO 协议解码错误
continue
}
switch message := message.(type) {
case ResponseMessage:
seq := message.GetResponse().RequestSeq
if await, ok := conn.awaitMap[seq]; ok {
await <- content
delete(conn.awaitMap, seq)
continue
}
}
if conn.handler != nil {
conn.handler.Handle(conn, message)
}
}
for k, v := range conn.awaitMap {
v <- nil
delete(conn.awaitMap, k)
}
}
func (conn *Conn) Close() error {
if conn.io != nil {
return conn.io.Close()
}
return nil
}