-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecho_tcp.go
88 lines (74 loc) · 1.72 KB
/
echo_tcp.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
package echo
import (
"context"
"errors"
"fmt"
"io"
"net"
)
var (
ErrListenerFail = errors.New("starting listener is failed")
ErrNoAddress = errors.New("server address is not defined")
)
// EchoTCP keeps net.Listener and verbose status.
type EchoTCP struct {
listener net.Listener
verbose bool
}
// NewEchoTCP returns a new EchoTCP.
func NewEchoTCP(address string, verbose bool) (*EchoTCP, error) {
if address == "" {
return nil, ErrNoAddress
}
l, err := Listen("tcp", address)
if err != nil {
return nil, fmt.Errorf("%w, error: %s", ErrListenerFail, err)
}
return &EchoTCP{
listener: l,
verbose: verbose,
}, nil
}
// Run starts accepting connections.
func (et *EchoTCP) Run(ctx context.Context) {
et.acceptConnections(ctx)
}
// acceptConnections accepts connects an handle them as goroutines.
// Runs until context is canceled.
func (et *EchoTCP) acceptConnections(ctx context.Context) {
for {
if ctx.Err() != nil {
fmt.Println("context is canceled")
return
}
conn, err := et.listener.Accept()
if err != nil {
fmt.Printf("error: %s\n", err)
continue
}
go handleConnection(conn)
}
}
// handleConnection reads from the client.
// Sends back to the originating source any data it receives. (rfc 862)
// Runs until client closes the connection.
func handleConnection(conn net.Conn) {
defer conn.Close()
cAddr := conn.RemoteAddr().String()
fmt.Printf("client %s is connected\n", cAddr)
buf := make([]byte, 1024)
for {
size, err := conn.Read(buf[:])
if err != nil {
if err != io.EOF {
fmt.Printf("error: %s\n", err)
}
fmt.Printf("client %s is disconnected\n", cAddr)
return
}
_, err = conn.Write(buf[:size])
if err != nil {
fmt.Printf("error: %s\n", err)
}
}
}