源代码chat.go
package main
import (
"bufio"
"fmt"
"log"
"net"
"strings"
)
const (
NickName int = iota
JoinRoom
ListRooms
SendMessage
QuitChat
)
const (
NickNameCommand = "#nick"
JoinRoomCommand = "#join"
ListRoomsCommand = "#rooms"
SendMessageCommand = "#msg"
QuitChatCommand = "#quit"
)
type room struct {
name string
members map[net.Addr]*client
}
func (r *room) broadcast(c *client, msg string) {
for addr, m := range r.members {
if c.conn.RemoteAddr() != addr {
m.msg(msg)
}
}
}
type command struct {
id int
client *client
args []string
}
type server struct {
rooms map[string]*room
commands chan command
}
func (s *server) run() {
for cmd := range s.commands {
switch cmd.id {
case NickName:
s.nickname(cmd.client, cmd.args)
case JoinRoom:
s.join(cmd.client, cmd.args)
case ListRooms:
s.list(cmd.client)
case SendMessage:
s.msg(cmd.client, cmd.args)
case QuitChat:
s.quit(cmd.client)
default:
log.Fatal("未知命令")
}
}
}
func (s *server) newC