-
Notifications
You must be signed in to change notification settings - Fork 1
/
listener_test.go
69 lines (59 loc) · 1.55 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
package water_test
import (
"context"
"fmt"
"net"
"github.com/refraction-networking/water"
_ "github.com/refraction-networking/water/transport/v1"
)
// ExampleListener demonstrates how to use water.Listener.
//
// This example is expected to demonstrate how to use the LATEST version of
// W.A.T.E.R. API, while other older examples could be found under transport/vX,
// where X is the version number (e.g. v0, v1, etc.).
//
// It is worth noting that unless the W.A.T.E.R. API changes, the version upgrade
// does not bring any essential changes to this example other than the import
// path and wasm file path.
func ExampleListener() {
config := &water.Config{
TransportModuleBin: wasmReverse,
ModuleConfigFactory: water.NewWazeroModuleConfigFactory(),
}
waterListener, err := config.ListenContext(context.Background(), "tcp", "localhost:0")
if err != nil {
panic(err)
}
defer waterListener.Close() // skipcq: GO-S2307
tcpConn, err := net.Dial("tcp", waterListener.Addr().String())
if err != nil {
panic(err)
}
defer tcpConn.Close() // skipcq: GO-S2307
waterConn, err := waterListener.Accept()
if err != nil {
panic(err)
}
defer waterConn.Close() // skipcq: GO-S2307
var msg = []byte("hello")
n, err := tcpConn.Write(msg)
if err != nil {
panic(err)
}
if n != len(msg) {
panic("short write")
}
buf := make([]byte, 1024)
n, err = waterConn.Read(buf)
if err != nil {
panic(err)
}
if n != len(msg) {
panic("short read")
}
if err := waterConn.Close(); err != nil {
panic(err)
}
fmt.Println(string(buf[:n]))
// Output: olleh
}