forked from panjf2000/gnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgnet.go
More file actions
216 lines (194 loc) 路 6.63 KB
/
Copy pathgnet.go
File metadata and controls
216 lines (194 loc) 路 6.63 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// Copyright 2019 Andy Pan. All rights reserved.
// Copyright 2018 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package gnet
import (
"errors"
"net"
"os"
"strings"
"time"
"github.com/panjf2000/gnet/netpoll"
)
var (
// ErrClosing indicates this server is closing.
ErrClosing = errors.New("closing")
)
const connRingBufferSize = 1024
// Action is an action that occurs after the completion of an event.
type Action int
const (
// None indicates that no action should occur following an event.
None Action = iota
// DataRead indicates data in buffer has been read.
DataRead
// Close closes the connection.
Close
// Shutdown shutdowns the server.
Shutdown
)
// Server represents a server context which provides information about the
// running server and has control functions for managing state.
type Server struct {
// Multicore indicates whether the server will be effectively created with multi-cores, if so,
// then you must take care with synchonizing memory between all event callbacks, otherwise,
// it will run the server with single thread. The number of threads in the server will be automatically
// assigned to the value of runtime.NumCPU().
Multicore bool
// The addrs parameter is an array of listening addresses that align
// with the addr strings passed to the Serve function.
Addr net.Addr
// NumLoops is the number of loops that the server is using.
NumLoops int
}
// Conn is an gnet connection.
type Conn interface {
// Context returns a user-defined context.
Context() interface{}
// SetContext sets a user-defined context.
SetContext(interface{})
// LocalAddr is the connection's local socket address.
LocalAddr() net.Addr
// RemoteAddr is the connection's remote peer address.
RemoteAddr() net.Addr
// Wake triggers a React event for this connection.
//Wake()
// ReadPair reads all data from ring buffer.
ReadPair() ([]byte, []byte)
// ReadBytes reads all data and return a new slice.
ReadBytes() []byte
// ResetBuffer resets the ring buffer.
ResetBuffer()
// AyncWrite writes data asynchronously.
AsyncWrite(buf []byte)
}
// EventHandler represents the server events' callbacks for the Serve call.
// Each event has an Action return value that is used manage the state
// of the connection and server.
type EventHandler interface {
// OnInitComplete fires when the server can accept connections. The server
// parameter has information and various utilities.
OnInitComplete(server Server) (action Action)
// OnOpened fires when a new connection has opened.
// The info parameter has information about the connection such as
// it's local and remote address.
// Use the out return value to write data to the connection.
// The opts return value is used to set connection options.
OnOpened(c Conn) (out []byte, action Action)
// OnClosed fires when a connection has closed.
// The err parameter is the last known connection error.
OnClosed(c Conn, err error) (action Action)
// PreWrite fires just before any data is written to any client socket.
PreWrite()
// React fires when a connection sends the server data.
// The in parameter is the incoming data.
// Use the out return value to write data to the connection.
React(c Conn) (out []byte, action Action)
// Tick fires immediately after the server starts and will fire again
// following the duration specified by the delay return value.
Tick() (delay time.Duration, action Action)
}
// EventServer is a built-in implementation of EventHandler which sets up each method with a default implementation,
// you can compose it with your own implementation of EventHandler when you don't want to implement all methods in EventHandler.
type EventServer struct {
}
// OnInitComplete fires when the server can accept connections. The server
// parameter has information and various utilities.
func (es *EventServer) OnInitComplete(svr Server) (action Action) {
return
}
// OnOpened fires when a new connection has opened.
// The info parameter has information about the connection such as
// it's local and remote address.
// Use the out return value to write data to the connection.
// The opts return value is used to set connection options.
func (es *EventServer) OnOpened(c Conn) (out []byte, action Action) {
return
}
// OnClosed fires when a connection has closed.
// The err parameter is the last known connection error.
func (es *EventServer) OnClosed(c Conn, err error) (action Action) {
return
}
// PreWrite fires just before any data is written to any client socket.
func (es *EventServer) PreWrite() {
}
// React fires when a connection sends the server data.
// The in parameter is the incoming data.
// Use the out return value to write data to the connection.
func (es *EventServer) React(c Conn) (out []byte, action Action) {
return
}
// Tick fires immediately after the server starts and will fire again
// following the duration specified by the delay return value.
func (es *EventServer) Tick() (delay time.Duration, action Action) {
return
}
// Serve starts handling events for the specified addresses.
//
// Addresses should use a scheme prefix and be formatted
// like `tcp://192.168.0.10:9851` or `unix://socket`.
// Valid network schemes:
// tcp - bind to both IPv4 and IPv6
// tcp4 - IPv4
// tcp6 - IPv6
// udp - bind to both IPv4 and IPv6
// udp4 - IPv4
// udp6 - IPv6
// unix - Unix Domain Socket
//
// The "tcp" network scheme is assumed when one is not specified.
func Serve(eventHandler EventHandler, addr string, opts ...Option) error {
var ln listener
defer ln.close()
options := initOptions(opts...)
ln.network, ln.addr = parseAddr(addr)
if ln.network == "unix" {
sniffError(os.RemoveAll(ln.addr))
}
var err error
if ln.network == "udp" {
if options.ReusePort {
ln.pconn, err = netpoll.ReusePortListenPacket(ln.network, ln.addr)
} else {
ln.pconn, err = net.ListenPacket(ln.network, ln.addr)
}
} else {
if options.ReusePort {
ln.ln, err = netpoll.ReusePortListen(ln.network, ln.addr)
} else {
ln.ln, err = net.Listen(ln.network, ln.addr)
}
}
if err != nil {
return err
}
if ln.pconn != nil {
ln.lnaddr = ln.pconn.LocalAddr()
} else {
ln.lnaddr = ln.ln.Addr()
}
if err := ln.system(); err != nil {
return err
}
return serve(eventHandler, &ln, options)
}
func parseAddr(addr string) (network, address string) {
network = "tcp"
address = addr
if strings.Contains(address, "://") {
network = strings.Split(address, "://")[0]
address = strings.Split(address, "://")[1]
}
return
}
type listener struct {
ln net.Listener
lnaddr net.Addr
pconn net.PacketConn
f *os.File
fd int
network string
addr string
}