-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
72 lines (59 loc) · 1.16 KB
/
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
package test1
import (
"bufio"
"encoding/json"
"fmt"
"net"
"time"
)
func TcpServer(tcpPort string) {
listener, err := net.Listen("tcp", tcpPort)
if err != nil {
fmt.Println(err)
return
}
defer func() {
listener.Close()
}()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
break
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
// Close connection when this function ends
defer func() {
conn.Close()
}()
timeoutDuration := 5 * time.Second
bufReader := bufio.NewReader(conn)
for {
// Set a deadline for reading. Read operation will fail if no data
// is received after deadline.
conn.SetReadDeadline(time.Now().Add(timeoutDuration))
// Read tokens delimited by newline
bytes, err := bufReader.ReadBytes('\n')
if err != nil {
fmt.Println(err)
return
}
var cmd Cmd
err2 := json.Unmarshal(bytes, &cmd)
if err2 != nil {
conn.Write([]byte("Json error."))
return
}
_, err = validateData(cmd)
if err != nil {
conn.Write([]byte(`{"status": "failure"}`))
return
}
channelCmd <- cmd
data := []byte(`{"status": "success"}`)
conn.Write([]byte(data))
}
}