IM-System版本0.7实现超时强踢

This commit is contained in:
wandoubaba 2024-11-25 11:16:58 +08:00
parent 9e012b21b7
commit 6759cf4af0

View File

@ -4,7 +4,9 @@ import (
"fmt" "fmt"
"io" "io"
"net" "net"
"runtime"
"sync" "sync"
"time"
) )
type Server struct { type Server struct {
@ -53,6 +55,8 @@ func (server *Server) Handler(conn net.Conn) {
// 用户上线, 将用户加入到OnlineMap中 // 用户上线, 将用户加入到OnlineMap中
user.Online() user.Online()
// 监听用户是否活跃的channel
isLive := make(chan bool)
// 接收客户端发送的消息 // 接收客户端发送的消息
go func() { go func() {
@ -71,10 +75,28 @@ func (server *Server) Handler(conn net.Conn) {
msg := string(buf[:n-1]) msg := string(buf[:n-1])
// 将得到的消息进行广播 // 将得到的消息进行广播
user.DoMessage(msg) user.DoMessage(msg)
// 用户的任意消息代表当前用户是一个活跃的将true发给isLive管道
isLive <- true
} }
}() }()
// 当前handler阻塞 // 设定定时器实现超时强踢
select {} for {
select {
case <-isLive:
// 当前用户是活跃的,应该重置定时器
// 不做任何事情为了激活select更新下面的定时器
// 只要执行time.After即实现重置定时器
case <-time.After(time.Second * 10):
// 已经超时将当前User强制关闭
user.SendMsg("你被踢了")
// 销毁用户的资源
close(user.C)
// 关闭连接
conn.Close()
// 退出
runtime.Goexit() // return
}
}
} }
// Server类的成员方法启动服务器的接口 // Server类的成员方法启动服务器的接口