forked from bostongolang/golang-lab-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.go
94 lines (75 loc) · 1.95 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 (
"log"
"net"
)
type ChatRoom struct {
// TODO: populate this
}
// NewChatRoom will create a chatroom
func NewChatRoom() *ChatRoom {
// TODO: initialize struct members
return &ChatRoom{}
}
func (cr *ChatRoom) ListenForMessages() {}
func (cr *ChatRoom) Logout(username string) {}
func (cr *ChatRoom) Join(conn net.Conn) {}
func (cr *ChatRoom) Broadcast(msg string) {}
type ChatUser struct {
// TODO: populate this
}
func NewChatUser(conn net.Conn) *ChatUser {
// TODO: initialize chat user
return &ChatUser{}
}
func (cu *ChatUser) ReadIncomingMessages(chatroom *ChatRoom) {
// TODO: read incoming messages in a loop
}
func (cu *ChatUser) WriteOutgoingMessages(chatroom *ChatRoom) {
// TODO: wait for outgoing messages in a loop, and write them
}
func (cu *ChatUser) Login(chatroom *ChatRoom) error {
// TODO: login the user
return nil
}
func (cu *ChatUser) ReadLine() (string, error) {
// TODO: read a line from the socket
return "", nil
}
func (cu *ChatUser) WriteString(msg string) error {
// TODO: write a line from the socket
return nil
}
func (cu *ChatUser) Send(msg string) {
// TODO: put a message on the outgoing messages queue
}
func (cu *ChatUser) Close() {
// TODO: close the socket
}
//
// 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
chatroom.Join(conn)
}
}