1. 查看当前在线用户
2. 修改当前用户的名字
3. 发送私聊消息
func HandleConnect(conn net.Conn) {
defer conn.Close()
//保存登录用户到map中
addr := conn.RemoteAddr().String() //获取IP地址
client := Client{make(chan string), addr, addr}
onlineMap[addr] = client
go WriterMsgToClient(conn, client)
userInfo := "[" + addr + "]" + addr + ": login\n"
message <- userInfo
go func() {
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if err != nil {
fmt.Println("conn.Read err: ", err)
return
}
msg := string(buf[:n-1]) //读取到用户发送的消息
if msg == "who" && len(msg) == 3 {
conn.Write([]byte("user list:\n"))
for _, client := range onlineMap {
userInfo = "[" + client.Addr + "]" + client.Name + "\n"
conn.Write([]byte(userInfo))
}
} else if len(msg) >= 8 && msg[:7] == "rename|" {
newName := strings.Split(msg, "|")[1]
client.Name = newName
onlineMap[addr] = client
conn.Write([]byte("rename success.\n"))
} else {
//私聊的消息格式:[对方IP]消息内容
//群发消息:消息内容
reg := regexp.MustCompile(`\[(.*)\]`) //通过正则表达式获取对方IP地址
ip := reg.FindString(msg) //获取[ip],如果msg中没有[ip],就返回""
if ip != "" {
//私聊
msg = msg[len(ip):] //获取[ip]后面获取消息内容
ip = ip[1 : len(ip)-1] //获取[ip]中的ip地址
cli, ok := onlineMap[ip] //获取指定ip的Client对象
if ok {
//如果找到Client,那么就给该Client的通道写入消息
userInfo = "[" + client.Addr + "]" + client.Name + ":" + msg + "\n"
cli.C <- userInfo
} else {
//如果没有找到对应的Client,那么就输出下面内容
fmt.Println("没有此人!")
}
} else {
//群发消息
userInfo = "[" + client.Addr + "]" + client.Name + ":" + msg + "\n"
message <- userInfo
}
}
}
}()
for {
;
}
}