-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
115 lines (93 loc) · 2.07 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"fmt"
"io"
"net"
"sync"
"time"
)
type Server struct {
Ip string // IP address
Port int // port
OnlineMap map[string]*User // store the online users
mapLock sync.RWMutex // the mutex for online map
Message chan string // the channel for broadcasting the message
}
func NewServer(ip string, port int) *Server {
server := &Server{
Ip: ip,
Port: port,
OnlineMap: make(map[string]*User),
Message: make(chan string),
}
return server
}
// listen to the Message
func (this *Server) ListenMessage() {
for {
msg := <-this.Message
this.mapLock.Lock()
for _, cli := range this.OnlineMap { // send it to all clients
cli.C <- msg
}
this.mapLock.Unlock()
}
}
// broadcast the message to all the user online !
func (this *Server) BroadCast(user *User, msg string) {
sendMsg := "[" + user.Addr + "]" + user.Name + ": " + msg
this.Message <- sendMsg
}
func (this *Server) Handler(conn net.Conn) {
user := NewUser(conn, this)
user.Online()
isLive := make(chan bool)
go func() {
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if n == 0 { // if use ctrl+C to close the connection, the return n is 0
user.Offline()
return
}
if err != nil && err != io.EOF {
fmt.Println("Conn Read err:", err)
return
}
msg := string(buf[:n-1])
user.DoMessage(msg)
isLive <- true
}
}()
for {
select {
case <-isLive:
// the user is live, reset the timer
case <-time.After(time.Second * 100):
// time out , kick out
user.SendMsg("you are kicked out!\n")
close(user.C)
conn.Close()
}
}
}
func (this *Server) Start() {
// a socket listener
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port)) // connection type, address
if err != nil {
fmt.Println("Server Listen err: ", err)
return
}
defer listener.Close()
go this.ListenMessage()
for {
// accpet
conn, err := listener.Accept()
if err != nil {
fmt.Println("listener accept err:", err)
continue
}
// start a go routine, to do the handler
go this.Handler(conn)
}
}