-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpserver.go
54 lines (45 loc) · 1.09 KB
/
tcpserver.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 main
import (
"bufio"
"net"
"strings"
"github.com/monodop/devlog/log"
)
func startTcpListener(exitChannel chan bool, messageChannel chan string) {
address := ":9090"
listener, err := net.Listen("tcp4", address)
if err != nil {
log.Exception(err)
return
}
defer listener.Close()
log.Info("TCP server now listening on %s", address)
nextId := 1
for {
connection, err := listener.Accept()
if err != nil {
log.Exception(err)
return
}
id := nextId
nextId++
go handleConnection(connection, id, messageChannel)
}
}
func handleConnection(connection net.Conn, id int, messageChannel chan string) {
log.Info("Opened TCP connection %d to %s", id, connection.RemoteAddr().String())
defer log.Info("Closed TCP connection %d to %s", id, connection.RemoteAddr().String())
reader := bufio.NewReader(connection)
for {
data, err := reader.ReadString('\n')
if err != nil {
log.Exception(err)
return
}
line := strings.TrimSpace(string(data))
log.Info("%d: %s", id, line)
messageChannel <- line
connection.Write([]byte("Thanks\n"))
}
// connection.Close()
}