服务器块关键代码:

 

根据协议调用不同的命令,我这边以“who:”查询用户是否在线,“rename:XXX”进行用户名更改,“to:XXX:msg”触发私聊

 if len(msgStr)>7 && msgStr[:7]=="rename:" {
			this.server.userRename(this.Conn.RemoteAddr().String(),strings.Split(msgStr,":")[1])
		} else if len(msgStr)==4 && msgStr[:4]=="who:" {
			this.server.getUserList(this.Conn.RemoteAddr().String())
		}else if len(msgStr)>4 && msgStr[:3]=="to:" {
			if len(strings.Split(msgStr,":"))==3 {
				this.server.sendMsg(strings.Split(msgStr,":")[1],this.Conn.RemoteAddr().String(),
					this.Name,strings.Split(msgStr,":")[2])
			}
		}

 

根据命令查询相应的用户列表做对应操作。


func (this *Server) sendMsg(sendUsername string,fromUserip string,fromUsername string,msg string){
	this.userMutex.Lock()

	for _, v := range this.users {
		if v.Name == sendUsername {
			sendMsg := "[" + fromUserip +"]"+fromUsername+": " +msg+"\n"
			_,err := v.Conn.Write([]byte(sendMsg))
			if err != nil {
				fmt.Println("server brodCast err:",err)
			}
		}
	}

	this.userMutex.Unlock()
}

func (this *Server) getUserList(ip string) {
	this.userMutex.Lock()
	user ,ok := this.users[ip]
	if ok {

		for _, v := range this.users {
			sendMsg := "[" + v.Conn.RemoteAddr().String()+"]"+v.Name+"\n"
			_,err := user.Conn.Write([]byte(sendMsg))
			if err != nil {
				fmt.Println("server brodCast err:",err)
			}
		}

	} else {
		println("user no found!")
	}
	this.userMutex.Unlock()
}

func (this *Server) userRename(ip string,name string) {
	this.userMutex.Lock()
	_ ,ok := this.users[ip]
	if ok {
		this.users[ip].Name = name
	} else {
		println("user no found!")
	}
	this.userMutex.Unlock()
}

 

实现效果:

 

 

目录: