-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
62 lines (50 loc) · 887 Bytes
/
main.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
package main
import (
"bufio"
"log"
"net"
"sync"
)
func main() {
addr := "localhost:9000"
sock, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
defer sock.Close()
log.Println("Started listening on:", addr)
stream := make(chan []byte)
clients := make(map[*net.Conn]bool)
var mutex sync.Mutex
go func() { // broadcast messages
for {
msg := <-stream
mutex.Lock()
for c := range clients {
(*c).Write(msg)
}
mutex.Unlock()
}
}()
for {
conn, err := sock.Accept()
if err != nil {
continue
}
mutex.Lock()
clients[&conn] = true
mutex.Unlock()
go func(conn net.Conn) {
defer conn.Close()
id := conn.RemoteAddr().String()
reader := bufio.NewReader(conn)
for {
line, err := reader.ReadString('\n')
if err != nil {
continue
}
stream <- []byte(id + ": " + line)
}
}(conn)
}
}