-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservice_test.go
157 lines (130 loc) · 2.47 KB
/
service_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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package smux
import (
"encoding/binary"
"fmt"
"net"
"sync"
"sync/atomic"
"testing"
"time"
)
var (
aioConns = map[uint16]*AIOConn{}
aioLock = sync.Mutex{}
aioService *AIOService
taskQueue chan func()
)
func init() {
taskQueue = make(chan func(), 128)
go func() {
for {
taskFunc := <-taskQueue
taskFunc()
}
}()
}
type AIOConn struct {
conn *MuxConn
service *AIOService
}
func (this *AIOConn) doWrite() {
}
func (this *AIOConn) doRead() {
taskQueue <- func() {
buf := make([]byte, 128)
n, err := this.conn.Read(buf)
if err == nil {
n, err = this.conn.Write(buf[:n])
}
if err != nil {
fmt.Println("error", this.conn.ID(), err)
if err != ErrNonblock {
this.service.Unwatch(this.conn.ID())
}
}
}
}
func (this *AIOConn) onEventCallback(event Event) {
//fmt.Println("onEventCallback", this.conn.ID(), event)
if event.Readable() {
this.doRead()
}
if event.Writable() {
this.doWrite()
}
}
func TestAIOService(t *testing.T) {
ln, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Error(err)
return
}
go func() {
conn, err := ln.Accept()
if err != nil {
return
}
go server(conn, t)
}()
addr := ln.Addr().String()
conn, err := net.Dial("tcp", addr)
if err != nil {
t.Error(err)
return
}
client(conn, t)
}
func server(conn net.Conn, t *testing.T) {
session := NewMuxSession(conn)
aioService = OpenAIOService(session, 1)
go func() {
for {
conn, err := session.Accept()
if err != nil {
t.Error(err)
return
}
//t.Log("conn", conn.ID())
aioConn := &AIOConn{conn: conn, service: aioService}
aioLock.Lock()
aioConns[conn.ID()] = aioConn
aioLock.Unlock()
conn.SetNonblock(true)
aioService.Watch(conn.ID(), aioConn.onEventCallback)
}
}()
}
func client(conn net.Conn, t *testing.T) {
session := NewMuxSession(conn)
wg := sync.WaitGroup{}
var count uint32 = 0
for i := 0; i < 2; i++ {
conn, _ := session.Open()
wg.Add(1)
data := make([]byte, 4)
binary.BigEndian.PutUint32(data, uint32(i))
//t.Log("open", conn.ID())
go func(conn *MuxConn) {
defer wg.Done()
defer conn.Close()
_, err := conn.Write(data)
if err != nil {
t.Error(err)
return
}
buf := make([]byte, 12)
n, err := conn.Read(buf)
if err != nil {
t.Error(err)
return
}
k := atomic.AddUint32(&count, 1)
t.Log(buf[:n], k)
}(conn)
}
wg.Wait()
t.Log(" --------- wait end")
time.Sleep(time.Second)
session.Close()
time.Sleep(time.Second * 2)
}