98 lines
1.8 KiB
Go
98 lines
1.8 KiB
Go
package server
|
|
|
|
import (
|
|
"net"
|
|
"sync"
|
|
|
|
cRPC "git.loafle.net/commons_go/rpc"
|
|
"git.loafle.net/commons_go/rpc/protocol/json"
|
|
"git.loafle.net/commons_go/server"
|
|
"git.loafle.net/overflow/overflow_discovery/discovery"
|
|
)
|
|
|
|
func newSocketHandler(rpcSH RPCServletHandler) SocketHandler {
|
|
sh := &SocketHandlers{
|
|
rpcSH: rpcSH,
|
|
}
|
|
|
|
return sh
|
|
}
|
|
|
|
type SocketHandlers struct {
|
|
server.SocketHandlers
|
|
|
|
rpcSH RPCServletHandler
|
|
}
|
|
|
|
func (sh *SocketHandlers) Init(serverCTX server.ServerContext) error {
|
|
if err := sh.SocketHandlers.Init(serverCTX); nil != err {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (sh *SocketHandlers) Handshake(serverCTX server.ServerContext, conn net.Conn) (id string) {
|
|
return "discovery"
|
|
}
|
|
|
|
func (sh *SocketHandlers) OnConnect(soc server.Socket) {
|
|
sh.SocketHandlers.OnConnect(soc)
|
|
|
|
soc.Context().SetAttribute(cRPC.ContentTypeKey, json.Name)
|
|
|
|
}
|
|
|
|
func (sh *SocketHandlers) Handle(soc server.Socket, stopChan <-chan struct{}, doneChan chan<- error) {
|
|
var err error
|
|
rpcServlet := retainRPCServlet(sh.rpcSH)
|
|
discovery.RPCServlet = rpcServlet
|
|
|
|
defer func() {
|
|
releaseRPCServlet(rpcServlet)
|
|
doneChan <- err
|
|
}()
|
|
|
|
rpcDoneChan := make(chan error, 1)
|
|
|
|
if err = rpcServlet.Start(soc.Context(), soc, rpcDoneChan); nil != err {
|
|
return
|
|
}
|
|
|
|
select {
|
|
case err = <-rpcDoneChan:
|
|
case <-stopChan:
|
|
rpcServlet.Stop()
|
|
}
|
|
|
|
}
|
|
|
|
func (sh *SocketHandlers) OnDisconnect(soc server.Socket) {
|
|
|
|
sh.SocketHandlers.OnDisconnect(soc)
|
|
}
|
|
|
|
func (sh *SocketHandlers) Destroy() {
|
|
|
|
sh.SocketHandlers.Destroy()
|
|
}
|
|
|
|
func (sh *SocketHandlers) Validate() {
|
|
|
|
}
|
|
|
|
var rpcServletPool sync.Pool
|
|
|
|
func retainRPCServlet(sh RPCServletHandler) cRPC.Servlet {
|
|
v := rpcServletPool.Get()
|
|
if v == nil {
|
|
return cRPC.NewServlet(sh)
|
|
}
|
|
return v.(cRPC.Servlet)
|
|
}
|
|
|
|
func releaseRPCServlet(s cRPC.Servlet) {
|
|
|
|
rpcServletPool.Put(s)
|
|
}
|