forked from gokcehan/lf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
143 lines (128 loc) · 2.54 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package main
import (
"bufio"
"fmt"
"log"
"net"
"os"
"strconv"
)
var (
gConnList = make(map[int]net.Conn)
gQuitChan = make(chan struct{}, 1)
gListener net.Listener
)
func serve() {
if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
panic(err)
}
defer f.Close()
log.SetOutput(f)
}
log.Print("hi!")
if gSocketProt == "unix" {
setUserUmask()
}
l, err := net.Listen(gSocketProt, gSocketPath)
if err != nil {
log.Printf("listening socket: %s", err)
return
}
defer l.Close()
gListener = l
listen(l)
}
func listen(l net.Listener) {
for {
c, err := l.Accept()
if err != nil {
select {
case <-gQuitChan:
log.Printf("bye!")
return
default:
log.Printf("accepting connection: %s", err)
}
}
go handleConn(c)
}
}
func echoerr(c net.Conn, msg string) {
fmt.Fprintln(c, msg)
log.Print(msg)
}
func echoerrf(c net.Conn, format string, a ...interface{}) {
echoerr(c, fmt.Sprintf(format, a...))
}
func handleConn(c net.Conn) {
s := bufio.NewScanner(c)
Loop:
for s.Scan() {
log.Printf("listen: %s", s.Text())
word, rest := splitWord(s.Text())
switch word {
case "conn":
if rest != "" {
word2, _ := splitWord(rest)
id, err := strconv.Atoi(word2)
if err != nil {
echoerr(c, "listen: conn: client id should be a number")
} else {
gConnList[id] = c
}
} else {
echoerr(c, "listen: conn: requires a client id")
}
case "drop":
if rest != "" {
word2, _ := splitWord(rest)
id, err := strconv.Atoi(word2)
if err != nil {
echoerr(c, "listen: drop: client id should be a number")
} else {
delete(gConnList, id)
}
} else {
echoerr(c, "listen: drop: requires a client id")
}
case "send":
if rest != "" {
word2, rest2 := splitWord(rest)
id, err := strconv.Atoi(word2)
if err != nil {
for _, c := range gConnList {
fmt.Fprintln(c, rest)
}
} else {
if c2, ok := gConnList[id]; ok {
fmt.Fprintln(c2, rest2)
} else {
echoerr(c, "listen: send: no such client id is connected")
}
}
}
case "quit":
if len(gConnList) == 0 {
gQuitChan <- struct{}{}
gListener.Close()
break Loop
}
case "quit!":
gQuitChan <- struct{}{}
for _, c := range gConnList {
fmt.Fprintln(c, "echo server is quitting...")
c.Close()
}
gListener.Close()
break Loop
default:
echoerrf(c, "listen: unexpected command: %s", word)
}
}
if s.Err() != nil {
echoerrf(c, "listening: %s", s.Err())
}
c.Close()
}