-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
85 lines (71 loc) · 1.17 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
package main
import (
"bufio"
"fmt"
"log"
"net"
)
const portNumber = ":3000"
var (
conns []net.Conn
connCh = make(chan net.Conn)
closeCh = make(chan net.Conn)
msgCh = make(chan string)
clientName string
)
func main() {
server, err := net.Listen("tcp", portNumber)
if err != nil {
log.Fatal(err)
}
go func() {
for {
conn, err := server.Accept()
if err != nil {
log.Fatal(err)
}
conns = append(conns, conn)
connCh <- conn
}
}()
for {
select {
case conn := <-connCh:
go onMessage(conn)
case msg := <-msgCh:
fmt.Print(msg)
case conn := <-closeCh:
fmt.Println("Client exit")
removeConn(conn)
}
}
// end main
}
func publishMsg(conn net.Conn, msg string) {
for i, _ := range conns {
if conns[i] != conn {
conns[i].Write([]byte(msg))
}
}
}
func removeConn(conn net.Conn) {
var i int
for i, _ = range conns {
if conns[i] == conn {
break
}
}
conns = append(conns[:i], conns[i+1:]...)
}
func onMessage(conn net.Conn) {
for {
reader := bufio.NewReader(conn)
msg, err := reader.ReadString('\n')
if err != nil {
break
}
msgCh <- msg
publishMsg(conn, msg)
}
closeCh <- conn
}