-
Notifications
You must be signed in to change notification settings - Fork 194
/
main.go
82 lines (68 loc) · 1.35 KB
/
main.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
package main
import (
"log"
"net/http"
_ "net/http/pprof"
"github.com/Allenxuxu/gev"
"github.com/Allenxuxu/toolkit/sync/atomic"
)
// Server example
type Server struct {
clientNum atomic.Int64
maxConnection int64
server *gev.Server
}
// New server
func New(ip, port string, maxConnection int64) (*Server, error) {
var err error
s := new(Server)
s.maxConnection = maxConnection
s.server, err = gev.NewServer(s,
gev.Address(ip+":"+port))
if err != nil {
return nil, err
}
return s, nil
}
// Start server
func (s *Server) Start() {
s.server.Start()
}
// Stop server
func (s *Server) Stop() {
s.server.Stop()
}
// OnConnect callback
func (s *Server) OnConnect(c *gev.Connection) {
s.clientNum.Add(1)
log.Println(" OnConnect : ", c.PeerAddr())
if s.clientNum.Get() > s.maxConnection {
_ = c.ShutdownWrite()
log.Println("Refused connection")
return
}
}
// OnMessage callback
func (s *Server) OnMessage(c *gev.Connection, ctx interface{}, data []byte) (out interface{}) {
log.Println("OnMessage")
out = data
return
}
// OnClose callback
func (s *Server) OnClose(c *gev.Connection) {
s.clientNum.Add(-1)
log.Println("OnClose")
}
func main() {
go func() {
if err := http.ListenAndServe(":6060", nil); err != nil {
panic(err)
}
}()
s, err := New("", "1833", 1)
if err != nil {
panic(err)
}
defer s.Stop()
s.Start()
}