-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (66 loc) · 1.2 KB
/
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
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
package main
import (
"bufio"
"fmt"
"log"
"net"
)
type client struct {
Nickname string
msg chan<- string
}
var (
entering = make(chan client)
leaving = make(chan client)
messages = make(chan string)
)
func main() {
log.Println("Welcome to GO-CHAT")
listener, err := net.Listen("tcp", "localhost:8080")
if err != nil {
panic(err.Error())
}
go broadcaster()
for {
cnn, err := listener.Accept()
if err != nil {
log.Println(err.Error())
continue
}
go handleConn(cnn)
}
}
func broadcaster() {
clients := make(map[client]bool)
for {
select {
case msg := <-messages:
for cli := range clients {
cli.msg <- msg
}
case cli := <-entering:
clients[cli] = true
case cli := <-leaving:
delete(clients, cli)
close(cli.msg)
}
}
}
func handleConn(conn net.Conn) {
ch := make(chan string)
go clientWritter(conn, ch)
who := conn.RemoteAddr().String()
cli := client{Nickname: who, msg: ch}
entering <- cli
input := bufio.NewScanner(conn)
for input.Scan() {
messages <- cli.Nickname + " said: " + input.Text()
}
leaving <- cli
conn.Close()
}
func clientWritter(conn net.Conn, ch <-chan string) {
for msg := range ch {
fmt.Fprintln(conn, msg)
}
}