-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.go
94 lines (86 loc) · 1.7 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
package main
import (
"bytes"
"log"
"net"
"strings"
)
type message struct {
user string
m string
}
type sub struct {
user string
out chan message
}
func clean(b []byte) string {
b = bytes.Trim(b, "\x00")
s := strings.TrimSpace(string(b))
return s
}
func read(conn net.Conn, user string, in chan<- message) {
// Error handling and EOF
for {
b := make([]byte, 256) // TODO learn to zero a buffer
_, e := conn.Read(b)
if e != nil {
log.Println("ERROR: ", e)
break
}
in <- message{clean(b), user}
}
}
func subscribe(s chan sub, in chan message) {
subs := make([]sub, 0)
for {
select {
case subscriber := <-s:
go func() {
in <- message{"server", subscriber.user + " logged in"}
var us string
for _, u := range subs {
us += "\n" + u.user
}
subscriber.out <- message{"server", "Online:" + us}
subs = append(subs, subscriber)
}()
case m := <-in:
for _, subscriber := range subs {
subscriber.out <- m
}
}
}
}
func handle(conn net.Conn, in chan<- message, out chan message, subs chan sub) {
w := "Welcome to chat!\n"
conn.Write([]byte(w))
w = "What do you want your nickname to be?\n"
conn.Write([]byte(w))
b := make([]byte, 16)
conn.Read(b)
user := clean(b)
subs <- sub{user, out}
go read(conn, user, in)
for m := range out {
conn.Write([]byte(m.user + ": " + m.m + "\n"))
}
}
func main() {
port := ":3030"
proto := "tcp"
ln, err := net.Listen(proto, port)
if err != nil {
log.Fatal("Couldn't listen on %s:\n%s", port, err)
}
in := make(chan message)
s := make(chan sub)
go subscribe(s, in)
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
}
out := make(chan message)
go handle(conn, in, out, s)
}
}