IM-System版本0.8实现简单私聊功能

This commit is contained in:
wandoubaba 2024-11-25 11:30:51 +08:00
parent 6759cf4af0
commit d3a8b24121
2 changed files with 26 additions and 1 deletions

View File

@ -86,7 +86,7 @@ func (server *Server) Handler(conn net.Conn) {
// 当前用户是活跃的,应该重置定时器
// 不做任何事情为了激活select更新下面的定时器
// 只要执行time.After即实现重置定时器
case <-time.After(time.Second * 10):
case <-time.After(time.Second * 3600):
// 已经超时将当前User强制关闭
user.SendMsg("你被踢了")
// 销毁用户的资源

View File

@ -82,6 +82,31 @@ func (user *User) DoMessage(msg string) {
// 自本人反馈一下改名成功
user.SendMsg(fmt.Sprintf("你已经修改用户名为%s\n", user.Name))
}
} else if len(msg) > 4 && msg[:3] == "to|" {
// 私聊消息格式to|name|content
if len(strings.Split(msg, "|")) != 3 {
user.SendMsg("私聊消息格式不正确,请使用\"to|name|content\"格式。\n")
return
}
// 获取对方的用户名
remoteName := strings.Split(msg, "|")[1]
if remoteName == "" {
user.SendMsg("私聊消息格式不正确,请使用\"to|name|content\"格式。\n")
return
}
// 根据用户名得到对方User对象
remoteUser, ok := user.server.OnlineMap[remoteName]
if !ok {
user.SendMsg("用户" + remoteName + "不存在\n")
return
}
// 获取消息内容通过对方的User对象将消息内容发送过去
content := strings.Split(msg, "|")[2]
if content == "" {
user.SendMsg("无消息内容,请重发\n")
return
}
remoteUser.SendMsg(user.Name + "对你说:" + content + "\n")
} else {
user.server.BroadCast(user, msg)
}