overflow_probe_container/server/socket_handlers.go

104 lines
2.1 KiB
Go
Raw Normal View History

2017-12-05 05:20:42 +00:00
package server
import (
"net"
"sync"
cRPC "git.loafle.net/commons_go/rpc"
"git.loafle.net/commons_go/rpc/protocol/json"
2017-12-05 05:34:07 +00:00
crsrs "git.loafle.net/commons_go/rpc/server/rwc/socket"
2017-12-05 05:20:42 +00:00
"git.loafle.net/commons_go/server"
2017-12-05 05:34:07 +00:00
oopc "git.loafle.net/overflow/overflow_probe_container"
2017-12-05 05:20:42 +00:00
)
func newSocketHandler(rpcSH RPCServletHandler) SocketHandler {
rpcRWCSH := crsrs.New()
sh := &SocketHandlers{
rpcSH: rpcSH,
rpcRWCSH: rpcRWCSH,
}
return sh
}
type SocketHandlers struct {
server.SocketHandlers
rpcRWCSH cRPC.ServletReadWriteCloseHandler
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(socketCTX server.SocketContext, 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)
2017-12-05 05:34:07 +00:00
soc.Context().SetAttribute(oopc.RPCServletKey, retainRPCServlet(sh.rpcSH, sh.rpcRWCSH))
2017-12-05 05:20:42 +00:00
}
func (sh *SocketHandlers) Handle(soc server.Socket, stopChan <-chan struct{}, doneChan chan<- error) {
var err error
2017-12-05 05:34:07 +00:00
rpcServlet := soc.Context().GetAttribute(oopc.RPCServletKey).(cRPC.Servlet)
2017-12-05 05:20:42 +00:00
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()
<-rpcDoneChan
}
}
func (sh *SocketHandlers) OnDisconnect(soc server.Socket) {
2017-12-05 05:34:07 +00:00
soc.Context().RemoveAttribute(oopc.RPCServletKey)
2017-12-05 05:20:42 +00:00
sh.SocketHandlers.OnDisconnect(soc)
}
func (sh *SocketHandlers) Destroy() {
sh.SocketHandlers.Destroy()
}
func (sh *SocketHandlers) Validate() {
}
var rpcServletPool sync.Pool
func retainRPCServlet(sh RPCServletHandler, rpcRWCSH cRPC.ServletReadWriteCloseHandler) cRPC.Servlet {
v := rpcServletPool.Get()
if v == nil {
return cRPC.NewServlet(sh, rpcRWCSH)
}
return v.(cRPC.Servlet)
}
func releaseRPCServlet(s cRPC.Servlet) {
rpcServletPool.Put(s)
}