-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_bufio_test.go
executable file
·109 lines (91 loc) · 1.93 KB
/
tcp_bufio_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
package libol
import (
"bufio"
"fmt"
"log"
"net"
"strings"
"sync"
"testing"
)
type Counter struct {
Rx int
Tx int
}
func handleConnection(conn net.Conn, n int, c *Counter) {
for i := 0; i < n; i++ {
// will listen for message to process ending in newline (\n)
message, _ := bufio.NewReader(conn).ReadString('\n')
if len(message) == 0 {
break
}
c.Rx += 1
// output message received
//fmt.Printf("Server Received: %s", string(message))
// sample process for string received
newMessage := strings.ToUpper(message)
// send new string back to client
conn.Write([]byte(newMessage))
}
}
func startServer(wg *sync.WaitGroup, ok chan int, n int, c *Counter) {
ln, err := net.Listen("tcp", "127.0.0.1:8081")
if err != nil {
log.Fatal(err)
}
ok <- 1
conn, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
handleConnection(conn, n, c)
conn.Close()
wg.Done()
}
func startClient(wg *sync.WaitGroup, ok chan int, n int, c *Counter) {
<-ok
addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:8081")
conn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
panic(err.Error())
}
go func() {
for {
message, _ := bufio.NewReader(conn).ReadString('\n')
//fmt.Printf("Client Received: %s", string(message))
if message != "" {
break
}
}
conn.Close()
wg.Done()
}()
go func() {
for i := 0; i < n; i++ {
fmt.Fprintf(conn, "From the client\n")
c.Tx += 1
}
}()
}
func TestClientAndServer(t *testing.T) {
wg := &sync.WaitGroup{}
ok := make(chan int, 1)
c := &Counter{}
wg.Add(1)
go startServer(wg, ok, 128, c)
wg.Add(1)
go startClient(wg, ok, 128, c)
wg.Wait()
//fmt.Printf("Total tx: %d, rx: %d\n", c.Tx, c.Rx)
}
func BenchmarkClientAndServer(b *testing.B) {
wg := &sync.WaitGroup{}
ok := make(chan int, 1)
c := &Counter{}
wg.Add(1)
go startServer(wg, ok, b.N, c)
wg.Add(1)
go startClient(wg, ok, b.N, c)
wg.Wait()
//fmt.Printf("Total tx: %d, rx: %d\n", c.Tx, c.Rx)
}