This repository has been archived by the owner on Dec 20, 2022. It is now read-only.
/
tcp-server.go
95 lines (89 loc) · 1.94 KB
/
tcp-server.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
package main
import (
"net"
"fmt"
"syscall"
"os/signal"
"bufio"
)
type ConnMessage struct {
Conn net.Conn
Message string
}
func main() {
connections := make(map[net.Conn]bool)
newMessages := make(chan ConnMessage)
go func() {
count := 0
for {
newMessages <- ConnMessage{nil, fmt.Sprintf("ping%d\r\n", count)}
count++
err := syscall.Sleep(1e10) //10 secs
if err != 0 {
return
}
}
}()
tcp, tcperr := net.ListenTCP("tcp", &net.TCPAddr{})
if tcperr != nil {
fmt.Println("Error opening TCP socket:", tcperr)
return
}
defer tcp.Close()
newConnections := make(chan *net.TCPConn)
fmt.Println("Listening on", tcp.Addr().Network(), tcp.Addr())
go func() {
for {
conn, connerr := tcp.AcceptTCP()
if connerr != nil {
fmt.Println("Error accepting TCP connection:", connerr)
} else {
newConnections <- conn
}
}
}()
for {
select {
case signal := <-signal.Incoming:
fmt.Println("got signal:", signal)
return
case conn := <-newConnections:
fmt.Printf("Got connection from %s %s\n",
conn.RemoteAddr().Network(),
conn.RemoteAddr())
conn.SetNoDelay(true)
conn.Write([]uint8("Hello\r\nHow are you?\r\n"))
connections[conn] = true
go func() {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
line, err := reader.ReadString('\n')
if err != nil {
//todo: remove conn from connections
fmt.Printf("error reading %s %s: %s\n",
conn.RemoteAddr().Network(),
conn.RemoteAddr(),
err)
connections[conn] = false, false
return //closes conn
}
newMessages <- ConnMessage{conn, string(line)}
}
}()
case msg := <-newMessages:
for conn, _ := range connections {
if conn != msg.Conn {
_, err := fmt.Fprintln(conn, msg.Message)
if err != nil {
fmt.Printf("error writing%s: %s\n",
conn,
conn.RemoteAddr(),
err)
connections[conn] = false, false
}
}
}
}
}
}