-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsimpleserver.go
71 lines (62 loc) · 1.32 KB
/
simpleserver.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
package main
import (
"bufio"
"fmt"
"log"
"net"
)
func main() {
// Setup server for all connections.
ln, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
log.Fatalln(err.Error())
}
defer ln.Close()
// We need channels for holding all connections, incoming connections, dead connections and messages.
var (
aconns = make(map[net.Conn]int)
conns = make(chan net.Conn)
dconns = make(chan net.Conn)
msgs = make(chan string)
i int
)
// Goroutine for accept incoming connections.
go func() {
for {
conn, err := ln.Accept()
if err != nil {
log.Fatalln(err.Error())
}
conns <- conn
}
}()
for {
select {
// Accept incoming connections.
case conn := <-conns:
aconns[conn] = i
i++
// Once we have the connection, we start reading message from it.
go func(conn net.Conn, i int) {
rd := bufio.NewReader(conn)
for {
m, err := rd.ReadString('\n')
if err != nil {
break
}
msgs <- fmt.Sprintf("Client %v: %v", i, m)
}
// This client close their connection.
dconns <- conn
}(conn, i)
case msg := <-msgs:
// We have to broadcast it to all connections.
for conn := range aconns {
conn.Write([]byte(msg))
}
case dconn := <-dconns:
log.Printf("Client %v was gone\n", aconns[dconn])
delete(aconns, dconn)
}
}
}