-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
98 lines (92 loc) · 1.94 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"fmt"
"io"
"net"
"sync"
"time"
)
type Server struct {
Ip string
Port int
OnlineMap map[string]*User
mapLock sync.RWMutex
}
func NewServer(ip string, port int) *Server {
server := &Server{
Ip: ip,
Port: port,
OnlineMap: make(map[string]*User),
}
return server
}
// Start 启动服务
func (s *Server) Start() {
listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.Ip, s.Port))
if err != nil {
panic(err)
return
}
fmt.Println("server启动成功")
defer listen.Close()
for {
conn, err := listen.Accept()
if err != nil {
fmt.Println(err)
return
}
go s.Handler(conn)
}
}
func (s *Server) Handler(conn net.Conn) {
defer conn.Close()
//用户上线
user := NewUser(conn, s)
user.OnLine()
//广播上线消息
s.Broadcast(user, "==Login==")
//监听用户是否活跃的channel
isAlive := make(chan bool, 1)
buf := make([]byte, 4096)
go func() {
for {
n, err := conn.Read(buf)
if n == 0 {
defer user.conn.Close()
user.OffLine()
fmt.Printf("[%s]-%s退出了群聊!\n", user.Addr, user.Name)
s.Broadcast(user, "退出了群聊!")
return
}
if err != nil && err != io.EOF {
fmt.Println(err)
return
}
//获取用户输入消息,n-1去掉回车符'\n'
msg := string(buf[:n-1])
//用户消息处理
user.DoMessage(msg)
isAlive <- true
}
}()
for {
select {
case <-isAlive:
//当前用户是活跃的,不做任何处理
case <-time.After(30 * time.Second):
//超时,将当前的用户强制下线
user.OffLine()
user.SendMsg("You are outed of timeout!")
fmt.Printf("[%s]-%s超时退出了\n", user.Addr, user.Name)
user.conn.Close()
return
}
}
}
// Broadcast 广播业务,将公共消息广播给所有用户
func (s *Server) Broadcast(user *User, msg string) {
sendMsg := fmt.Sprintf("[%s]%s:%s\n", user.Addr, user.Name, msg)
for _, user := range s.OnlineMap {
user.SendMsg(sendMsg)
}
}