-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpclient.go
54 lines (48 loc) · 1.13 KB
/
tcpclient.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
package jata
import (
"bufio"
"fmt"
"net"
)
// TCPClient represents a TCP Server
type TCPClient struct {
Listener *net.Listener
}
// StartListeningOnPort starts the server
func (s *TCPClient) StartListeningOnPort(port int) (err error) {
defer s.StopListening()
portString := fmt.Sprintf(":%d", port)
ln, err1 := net.Listen("tcp", portString)
if err1 != nil {
Error.Printf("StartListeningOnPort(%d) terminated due to %v", port, err1)
return err1
}
s.Listener = &ln
for {
conn, err2 := (*s.Listener).Accept()
if err2 == nil {
go HandleConnection(s, conn)
} else {
Error.Printf("StartListeningOnPort(%d) terminated due to %v", port, err2)
return err2
}
}
}
// StopListening closes the Listerner
func (s *TCPClient) StopListening() (err error) {
return (*s.Listener).Close()
}
// HandleConnection handles all connection logic
func HandleConnection(s *TCPClient, c net.Conn) {
defer c.Close()
reader := bufio.NewReaderSize(c, 8192)
for {
line, err := reader.ReadString('\n')
if err != nil {
Error.Printf("HandleConnection() terminated due to %v", err)
s.StopListening()
return
}
fmt.Print(line)
}
}