-
Notifications
You must be signed in to change notification settings - Fork 3
/
conn_test.go
112 lines (108 loc) · 2.14 KB
/
conn_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
// Copyright (c) 2020 Meng Huang (mhboy@outlook.com)
// This package is licensed under a MIT license that can be found in the LICENSE file.
package websocket
import (
"net"
"net/http"
"sync"
"testing"
"time"
)
func TestConn(t *testing.T) {
network := "tcp"
addr := ":8080"
Serve := func(conn *Conn) {
for {
msg, err := conn.ReadMessage(nil)
if err != nil {
break
}
conn.WriteMessage(msg)
}
conn.Close()
}
httpServer := &http.Server{
Addr: addr,
Handler: Handler(Serve),
}
l, _ := net.Listen(network, addr)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
httpServer.Serve(l)
}()
conn, err := Dial(network, addr, "/", nil)
if err != nil {
t.Error(err)
}
conn.SetBufferedInput(0)
conn.SetBufferedInput(bufferSize)
conn.SetBufferedOutput(0)
conn.SetBufferedOutput(bufferSize)
conn.SetBufferedOutput(bufferSize)
{
if err := conn.SetDeadline(time.Now().Add(time.Minute)); err != nil {
t.Error()
}
if err := conn.SetWriteDeadline(time.Now().Add(time.Minute)); err != nil {
t.Error()
}
if n, err := conn.Write(nil); err != nil {
t.Error(err)
} else if n > 0 {
t.Error(n)
}
msg := "Hello World"
if n, err := conn.Write([]byte(msg)); err != nil {
t.Error(err)
} else if n != len(msg) {
t.Error(n)
}
if n, err := conn.Read(nil); err != nil {
t.Error(err)
} else if n > 0 {
t.Error(n)
}
buf := make([]byte, 64)
if err := conn.SetReadDeadline(time.Now().Add(time.Minute)); err != nil {
t.Error()
}
n, err := conn.Read(buf)
if err != nil {
t.Error(err)
} else if string(buf[:n]) != msg {
t.Error(string(buf[:n]))
}
if addr := conn.LocalAddr(); addr == nil {
t.Error()
}
if addr := conn.RemoteAddr(); addr == nil {
t.Error()
}
}
{
msg := "Hello World"
if n, err := conn.Write([]byte(msg)); err != nil {
t.Error(err)
} else if n != len(msg) {
t.Error(n)
}
var str string
buf := make([]byte, 1)
for len(str) < len(msg) {
n, err := conn.Read(buf)
if err != nil {
t.Error(err)
} else if n > 0 {
str += string(buf)
}
}
if str != msg {
t.Error(str)
}
}
conn.Close()
httpServer.Close()
wg.Wait()
}