71 lines
2.6 KiB
Go
71 lines
2.6 KiB
Go
package server
|
|
|
|
import (
|
|
"go.uber.org/zap"
|
|
"minotaur/utils/log"
|
|
"minotaur/utils/runtimes"
|
|
"reflect"
|
|
)
|
|
|
|
type ConnectionReceivePacketEventHandle func(conn *Conn, packet []byte)
|
|
type ConnectionOpenedEventHandle func(conn *Conn)
|
|
type ConnectionClosedEventHandle func(conn *Conn)
|
|
|
|
type event struct {
|
|
*Server
|
|
connectionReceivePacketEventHandles []ConnectionReceivePacketEventHandle
|
|
connectionOpenedEventHandles []ConnectionOpenedEventHandle
|
|
connectionClosedEventHandles []ConnectionClosedEventHandle
|
|
}
|
|
|
|
// RegConnectionClosedEvent 在连接关闭后将立刻执行被注册的事件处理函数
|
|
func (slf *event) RegConnectionClosedEvent(handle ConnectionClosedEventHandle) {
|
|
if slf.network == NetworkHttp {
|
|
panic(ErrNetworkIncompatibleHttp)
|
|
}
|
|
slf.connectionClosedEventHandles = append(slf.connectionClosedEventHandles, handle)
|
|
log.Info("Server", zap.String("RegEvent", runtimes.CurrentRunningFuncName()), zap.String("handle", reflect.TypeOf(handle).String()))
|
|
}
|
|
|
|
func (slf *event) OnConnectionClosedEvent(conn *Conn) {
|
|
for _, handle := range slf.connectionClosedEventHandles {
|
|
handle(conn)
|
|
}
|
|
}
|
|
|
|
// RegConnectionOpenedEvent 在连接打开后将立刻执行被注册的事件处理函数
|
|
func (slf *event) RegConnectionOpenedEvent(handle ConnectionOpenedEventHandle) {
|
|
if slf.network == NetworkHttp {
|
|
panic(ErrNetworkIncompatibleHttp)
|
|
}
|
|
slf.connectionOpenedEventHandles = append(slf.connectionOpenedEventHandles, handle)
|
|
log.Info("Server", zap.String("RegEvent", runtimes.CurrentRunningFuncName()), zap.String("handle", reflect.TypeOf(handle).String()))
|
|
}
|
|
|
|
func (slf *event) OnConnectionOpenedEvent(conn *Conn) {
|
|
for _, handle := range slf.connectionOpenedEventHandles {
|
|
handle(conn)
|
|
}
|
|
}
|
|
|
|
// RegConnectionReceivePacketEvent 在接收到数据包时将立刻执行被注册的事件处理函数
|
|
func (slf *event) RegConnectionReceivePacketEvent(handle ConnectionReceivePacketEventHandle) {
|
|
if slf.network == NetworkHttp {
|
|
panic(ErrNetworkIncompatibleHttp)
|
|
}
|
|
slf.connectionReceivePacketEventHandles = append(slf.connectionReceivePacketEventHandles, handle)
|
|
log.Info("Server", zap.String("RegEvent", runtimes.CurrentRunningFuncName()), zap.String("handle", reflect.TypeOf(handle).String()))
|
|
}
|
|
|
|
func (slf *event) OnConnectionReceivePacketEvent(conn *Conn, packet []byte) {
|
|
for _, handle := range slf.connectionReceivePacketEventHandles {
|
|
handle(conn, packet)
|
|
}
|
|
}
|
|
|
|
func (slf *event) check() {
|
|
if slf.network != NetworkHttp && len(slf.connectionReceivePacketEventHandles) == 0 {
|
|
log.Warn("Server", zap.String("ConnectionReceivePacketEvent", "Invalid server, no packets processed"))
|
|
}
|
|
}
|