-
Notifications
You must be signed in to change notification settings - Fork 2
/
listener_test.go
82 lines (76 loc) · 2.02 KB
/
listener_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
package liblpc
import (
"fmt"
"github.com/gen-iot/std"
"net"
"testing"
"time"
)
func onAccept(ln *Listener, newFd int, err error) {
if err != nil {
stdLog("listener error:", err)
std.CloseIgnoreErr(ln)
return
}
stdLog("on accept , newfd = ", newFd)
stream := NewConnStream(ln.Loop().(*IOEvtLoop), newFd, func(sw StreamWriter, data []byte, len int) {
stdLog("onread", string(data[:len]))
})
stream.SetOnClose(func(sw StreamWriter, err error) {
stdLog("closed! err:", err)
sw.(*Stream).Loop().Break()
std.CloseIgnoreErr(sw)
})
stream.Start()
}
func localConTester() {
conn, err := net.Dial("tcp", "127.0.0.1:8001")
std.AssertError(err, "dial tcp 127.0.0.1:8001 failed")
defer std.CloseIgnoreErr(conn)
tm := time.After(time.Second * 10)
for {
select {
case <-tm:
return
default:
}
time.Sleep(time.Millisecond * 500)
_, err := conn.Write([]byte(fmt.Sprintf("hello , time -> %s", time.Now().String())))
std.AssertError(err, "conn write")
}
}
func TestListener(t *testing.T) {
sockaddr, err := ResolveTcpAddr("127.0.0.1:8001")
std.AssertError(err, "ResolveTcpAddr [127.0.0.1:8001]")
sockFd, err := NewListenerFd2(4, sockaddr, 128, true, true)
ioEvtLoop, err := NewIOEvtLoop(DefaultIOEvtLoopBufferSize)
std.AssertError(err, "new ioloop")
defer std.CloseIgnoreErr(ioEvtLoop)
//
fdListener := NewListener(ioEvtLoop, int(sockFd), onAccept)
fdListener.Start()
//
cliFd, err := NewConnFd2(4, sockaddr)
std.AssertError(err, "NewConnFd2")
fds := NewClientStream(ioEvtLoop, int(cliFd), func(sw StreamWriter, data []byte, len int) {
stdLog("onread", string(data[:len]))
})
fds.SetOnConnect(func(sw StreamWriter, err error) {
if err != nil {
stdLog("connected! err:", err)
return
}
time.AfterFunc(time.Second*3, func() {
std.CloseIgnoreErr(sw)
})
stdLog("connect success, will close after 3s")
})
fds.SetOnClose(func(sw StreamWriter, err error) {
stdLog("closed! err:", err)
sw.(*Stream).Loop().Break()
std.CloseIgnoreErr(sw)
})
fds.Start()
//go localConTester()
ioEvtLoop.Run(nil)
}