-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathchat.go
220 lines (191 loc) · 4.52 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package main
import (
"bufio"
"log"
"net"
)
//
// ChatRoom is the main chatroom data structure.
//
// `users` contains connected ChatUser connections.
// `incoming` receives incoming messages from ChatUser connections.
// `joins` receives incoming new ChatUser connections.
// `disconnects` receives disconnect notifications.
//
type ChatRoom struct {
users map[string]*ChatUser
incoming chan string
joins chan *ChatUser
disconnects chan string
}
//
// NewChatRoom() will create a new chatroom.
//
func NewChatRoom() *ChatRoom {
return &ChatRoom{
users: make(map[string]*ChatUser),
incoming: make(chan string),
joins: make(chan *ChatUser),
disconnects: make(chan string),
}
}
func (cr *ChatRoom) ListenForMessages() {
go func() {
for {
select {
case msg := <-cr.incoming:
cr.Broadcast(msg)
case user := <-cr.joins:
cr.users[user.username] = user
cr.Broadcast("*** " + user.username + " just joined the chatroom")
case username := <-cr.disconnects:
// perform the logout by removing
// the username from the `users` map if it exists.
// Also call Close() on the user object.
if cr.users[username] != nil {
cr.users[username].Close()
delete(cr.users, username)
cr.Broadcast("*** " + username + " has disconnected")
}
}
}
}()
}
func (cr *ChatRoom) Logout(username string) {
cr.disconnects <- username
}
func (cr *ChatRoom) Join(conn net.Conn) {
user := NewChatUser(conn)
if user.Login(cr) == nil {
cr.joins <- user
}
}
func (cr *ChatRoom) Broadcast(msg string) {
for _, user := range cr.users {
user.Send(msg)
}
}
//
// ChatUser contains information for the connected user.
//
// `conn` is the socket.
// `disconnect` indicates whether or not the socket is disconnected.
// `username` is the chat username.
// `outgoing` is a channel with all pending outgoing messages
// to be written to the socket.
// `reader` is the buffered socket read stream.
// `writer` is the buffered socket write stream.
//
type ChatUser struct {
conn net.Conn
disconnect bool
username string
outgoing chan string
reader *bufio.Reader
writer *bufio.Writer
}
func NewChatUser(conn net.Conn) *ChatUser {
writer := bufio.NewWriter(conn)
reader := bufio.NewReader(conn)
cu := &ChatUser{
conn: conn,
disconnect: false,
reader: reader,
writer: writer,
outgoing: make(chan string),
}
return cu
}
func (cu *ChatUser) ReadIncomingMessages(chatroom *ChatRoom) {
go func() {
for {
line, err := cu.ReadLine()
if cu.disconnect {
break
}
if err != nil {
chatroom.Logout(cu.username)
break
}
if line != "" {
chatroom.incoming <- ("[" + cu.username + "] " + line)
}
}
}()
}
func (cu *ChatUser) WriteOutgoingMessages(chatroom *ChatRoom) {
go func() {
for {
data := <-cu.outgoing
if cu.disconnect {
break
}
data = data + "\n"
err := cu.WriteString(data)
if err != nil {
chatroom.Logout(cu.username)
break
}
}
}()
}
func (cu *ChatUser) Login(chatroom *ChatRoom) error {
var err error
cu.WriteString("Welcome to Jen's chat server!\n")
cu.WriteString("Please enter your username: ")
cu.username, err = cu.ReadLine()
if err != nil {
return err
}
log.Println("User logged in:", cu.username)
cu.WriteString("Welcome, " + cu.username + "\n")
cu.WriteOutgoingMessages(chatroom)
cu.ReadIncomingMessages(chatroom)
return nil
}
func (cu *ChatUser) ReadLine() (string, error) {
bytes, _, err := cu.reader.ReadLine()
str := string(bytes)
return str, err
}
func (cu *ChatUser) WriteString(msg string) error {
_, err := cu.writer.WriteString(msg)
if err != nil {
return err
}
return cu.writer.Flush()
}
func (cu *ChatUser) Send(msg string) {
cu.outgoing <- msg
}
func (cu *ChatUser) Close() {
cu.disconnect = true
cu.conn.Close()
}
//
// main will create a socket, bind to port 6677,
// and loop while waiting for connections.
//
// When it receives a connection it will pass it to
// `chatroom.Join()`.
//
func main() {
log.Println("Chat server starting!")
chatroom := NewChatRoom()
// This binds the socket to TCP port 6677
// on all interfaces.
listener, err := net.Listen("tcp", ":6677")
chatroom.ListenForMessages()
if err != nil {
log.Fatal("Unable to bind to 6677", err)
}
// Accept a connection, and print out the remote
// address so we know who has connected.
for {
conn, _ := listener.Accept()
log.Println("Connection joined.", conn.RemoteAddr())
// run this in a goroutine so more than one thing
// can connect
go chatroom.Join(conn)
}
}