-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
68 lines (59 loc) · 1.05 KB
/
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
package main
import (
"bufio"
"fmt"
"net"
"os"
)
var packager = NewPackager()
var pool = NewWorkerPool(20)
func main() {
startServer(":8080")
}
func startServer(port string) {
ln, err := net.Listen("tcp", port)
if err != nil {
handleError("Listen", err)
os.Exit(1)
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
handleError("Accept", err)
os.Exit(1)
}
w := Work{
input: conn,
workable: func(c InputData) Result {
handleConnection(c.(net.Conn))
return 0
},
}
pool.input <- &w
//go handleConnection(conn)
}
}
func handleError(s string, err error) {
fmt.Println("ERROR:", s, err)
}
func handleConnection(conn net.Conn) {
defer conn.Close()
scanner := bufio.NewScanner(conn)
for {
scanner.Scan()
if err := scanner.Err(); err != nil {
handleError("Read", err)
break
}
msg := NewMessage(scanner.Text())
fmt.Println(msg)
result := packager.Process(msg)
fmt.Print(result)
_, err := conn.Write([]byte(result))
if err != nil {
handleError("Write", err)
break
}
}
}