Skip to content

Instantly share code, notes, and snippets.

@ebenoist
Created August 16, 2018 17:44
Show Gist options
  • Save ebenoist/82407eaee58865cc22d432470105856e to your computer and use it in GitHub Desktop.
Save ebenoist/82407eaee58865cc22d432470105856e to your computer and use it in GitHub Desktop.
Chat Server!
package main
import (
"bufio"
"fmt"
"log"
"net"
)
type Room struct {
Members []*Member
}
func (r *Room) Broadcast(msg string) {
for _, member := range r.Members {
member.Conn.Write([]byte(msg + "\n"))
}
}
func (r *Room) Welcome(conn net.Conn) {
conn.Write([]byte("weclome!\n"))
conn.Write([]byte("whats your name?\n"))
reader := bufio.NewReader(conn)
if name, _, err := reader.ReadLine(); err == nil {
member := &Member{Name: name, Conn: conn}
r.Members = append(r.Members, member)
r.Broadcast(fmt.Sprintf("%s has joined", member.Name))
go member.Talk(r)
}
}
type Member struct {
Conn net.Conn
Name []byte
}
func (m *Member) Talk(room *Room) {
reader := bufio.NewReader(m.Conn)
for {
msg, _, err := reader.ReadLine()
if err == nil {
room.Broadcast(fmt.Sprintf("%s: %s", m.Name, msg))
}
}
}
func main() {
listener, err := net.Listen("tcp", "0.0.0.0:3000")
if err != nil {
log.Fatalf("could not assign port - %s", err)
}
room := &Room{
Members: []*Member{},
}
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("could not connect - %s", err)
} else {
go room.Welcome(conn)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment