Golang TCP服务器用户修改名字查询用户在线以及私聊功能
Posted 卑微的小李
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Golang TCP服务器用户修改名字查询用户在线以及私聊功能相关的知识,希望对你有一定的参考价值。
服务器块关键代码:
根据协议调用不同的命令,我这边以“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()
实现效果:
目录:
以上是关于Golang TCP服务器用户修改名字查询用户在线以及私聊功能的主要内容,如果未能解决你的问题,请参考以下文章