overflow_discovery/server/socket_handlers.go

104 lines
2.0 KiB
Go
Raw Normal View History

2017-11-29 05:19:36 +00:00
package server
import (
"net"
2017-11-29 05:46:47 +00:00
"sync"
2017-11-29 05:19:36 +00:00
2017-11-29 05:46:47 +00:00
cRPC "git.loafle.net/commons_go/rpc"
2017-11-30 10:16:55 +00:00
crsrs "git.loafle.net/commons_go/rpc/server/rwc/socket"
2017-11-29 05:46:47 +00:00
"git.loafle.net/commons_go/rpc/protocol/json"
2017-11-29 05:19:36 +00:00
"git.loafle.net/commons_go/server"
2017-11-29 05:46:47 +00:00
"git.loafle.net/overflow/overflow_discovery/discovery"
2017-11-29 05:19:36 +00:00
)
func newSocketHandler(rpcSH RPCServletHandler) SocketHandler {
2017-11-30 10:16:55 +00:00
rpcRWCSH := crsrs.New()
2017-11-29 05:19:36 +00:00
sh := &SocketHandlers{
2017-11-30 10:16:55 +00:00
rpcSH: rpcSH,
rpcRWCSH: rpcRWCSH,
2017-11-29 05:19:36 +00:00
}
return sh
}
type SocketHandlers struct {
server.SocketHandlers
2017-11-30 10:16:55 +00:00
rpcRWCSH cRPC.ServletReadWriteCloseHandler
rpcSH RPCServletHandler
2017-11-29 05:19:36 +00:00
}
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) {
2017-11-29 05:46:47 +00:00
return "discovery"
2017-11-29 05:19:36 +00:00
}
func (sh *SocketHandlers) OnConnect(soc server.Socket) {
2017-11-29 05:46:47 +00:00
sh.SocketHandlers.OnConnect(soc)
soc.Context().SetAttribute(cRPC.ContentTypeKey, json.Name)
2017-11-29 05:19:36 +00:00
}
func (sh *SocketHandlers) Handle(soc server.Socket, stopChan <-chan struct{}, doneChan chan<- error) {
2017-11-29 05:46:47 +00:00
var err error
2017-11-30 10:16:55 +00:00
rpcServlet := retainRPCServlet(sh.rpcSH, sh.rpcRWCSH)
2017-11-29 05:46:47 +00:00
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()
2017-11-30 10:16:55 +00:00
<-rpcDoneChan
2017-11-29 05:46:47 +00:00
}
2017-11-29 05:19:36 +00:00
}
func (sh *SocketHandlers) OnDisconnect(soc server.Socket) {
sh.SocketHandlers.OnDisconnect(soc)
}
func (sh *SocketHandlers) Destroy() {
sh.SocketHandlers.Destroy()
}
func (sh *SocketHandlers) Validate() {
}
2017-11-29 05:46:47 +00:00
var rpcServletPool sync.Pool
2017-11-30 10:16:55 +00:00
func retainRPCServlet(sh RPCServletHandler, rpcRWCSH cRPC.ServletReadWriteCloseHandler) cRPC.Servlet {
2017-11-29 05:46:47 +00:00
v := rpcServletPool.Get()
if v == nil {
2017-11-30 10:16:55 +00:00
return cRPC.NewServlet(sh, rpcRWCSH)
2017-11-29 05:46:47 +00:00
}
return v.(cRPC.Servlet)
}
func releaseRPCServlet(s cRPC.Servlet) {
rpcServletPool.Put(s)
}