-
Notifications
You must be signed in to change notification settings - Fork 175
/
chat.go
122 lines (107 loc) · 2.19 KB
/
chat.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
// ex8.15 is a chat server that skips clients that are slow to process writes.
package main
import (
"bufio"
"fmt"
"log"
"net"
"time"
)
const timeout = 10 * time.Second
type client struct {
Out chan<- string // outgoing message channel
Name string
}
var (
entering = make(chan client)
leaving = make(chan client)
messages = make(chan string) // all incoming client messages
)
func broadcaster() {
clients := make(map[client]bool) // all connected clients
for {
select {
case msg := <-messages:
// Broadcast incoming message to all
// clients' outgoing message channels.
for cli := range clients {
select {
case cli.Out <- msg:
default:
// Skip client if it's reading messages slowly.
}
}
case cli := <-entering:
clients[cli] = true
cli.Out <- "Present:"
for c := range clients {
cli.Out <- c.Name
}
case cli := <-leaving:
delete(clients, cli)
close(cli.Out)
}
}
}
func handleConn(conn net.Conn) {
out := make(chan string, 10) // outgoing client messages
go clientWriter(conn, out)
in := make(chan string) // incoming client messages
go clientReader(conn, in)
var who string
nameTimer := time.NewTimer(timeout)
out <- "Enter your name:"
select {
case name := <-in:
who = name
case <-nameTimer.C:
conn.Close()
return
}
cli := client{out, who}
out <- "You are " + who
messages <- who + " has arrived"
entering <- cli
idle := time.NewTimer(timeout)
Loop:
for {
select {
case msg := <-in:
messages <- who + ": " + msg
idle.Reset(timeout)
case <-idle.C:
conn.Close()
break Loop
}
}
leaving <- cli
messages <- who + " has left"
conn.Close()
}
func clientWriter(conn net.Conn, ch <-chan string) {
for msg := range ch {
fmt.Fprintln(conn, msg) // NOTE: ignoring network errors
}
}
func clientReader(conn net.Conn, ch chan<- string) {
input := bufio.NewScanner(conn)
for input.Scan() {
ch <- input.Text()
}
// NOTE: ignoring potential errors from input.Err()
}
func main() {
listener, err := net.Listen("tcp", "localhost:8000")
if err != nil {
log.Fatal(err)
}
go broadcaster()
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err)
continue
}
go handleConn(conn)
}
}