-
Notifications
You must be signed in to change notification settings - Fork 15
/
client.go
56 lines (46 loc) · 833 Bytes
/
client.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
package main
import (
"bytes"
"context"
"log"
"net"
"time"
"github.com/lesismal/nbio"
)
func main() {
var (
addr = "127.0.0.1:8888"
request = []byte("hello")
)
g := nbio.NewEngine(nbio.Config{})
done := make(chan int)
g.OnData(func(c *nbio.Conn, response []byte) {
log.Println("onData:", string(response))
if !bytes.Equal(request, response) {
log.Panic("not equal")
}
close(done)
})
err := g.Start()
if err != nil {
log.Panic(err)
}
defer g.Stop()
c, err := net.Dial("udp", addr)
if err != nil {
log.Panic(err)
}
nbc, err := g.AddConn(c)
if err != nil {
log.Panic(err)
}
nbc.Write(request)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
select {
case <-ctx.Done():
log.Println("timeout")
case <-done:
log.Println("success")
}
}