-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_server.go
75 lines (62 loc) · 1.43 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
package main
import (
"bufio"
"fmt"
"net"
"time"
)
const (
connType = "tcp"
connHost = "localhost"
connPort = "2019"
timeoutSec = 30
reqPerSec = 30
)
var (
locations = make(chan string, 100)
)
func main() {
listener, err := net.Listen(connType, connHost+":"+connPort)
if err != nil {
fmt.Println("Listen error: ", err)
return
}
defer listener.Close()
fmt.Println("Starting listening...")
rateLimit := time.Second / reqPerSec
rateLimiter := time.Tick(rateLimit)
go func() {
for location := range locations {
<-rateLimiter
go requestWeatherInLoc(location)
}
}()
for {
c, err := listener.Accept()
if err != nil {
fmt.Println("Accept error: ", err)
break
}
// Start a new goroutine to handle the new connection.
go handleConn(c)
}
}
func handleConn(conn net.Conn) {
defer conn.Close()
conn.Write([]byte("Please enter a distict in Taipei City (for example, 信義區, 松山區, etc.) to get the weather information or ‘quit’ to quit.\n"))
scanner := bufio.NewScanner(conn)
timeoutDuration := timeoutSec * time.Second
for {
conn.SetDeadline(time.Now().Add(timeoutDuration))
if !scanner.Scan() || scanner.Text() == "quit" {
break
}
conn.Write([]byte("Message received.\n"))
location := scanner.Text()
fmt.Println("Received location:", location, "from", conn.RemoteAddr())
locations <- location
}
if err := scanner.Err(); err != nil {
fmt.Println("Scanner error:", err)
}
}