server-go/server-rwc-handler.go
crusader aaed2f9fe3 ing
2018-04-04 22:28:35 +09:00

82 lines
1.8 KiB
Go

package server
import (
"sync"
logging "git.loafle.net/commons/logging-go"
)
type ServerRWCHandler struct {
connections sync.Map
ReadwriteHandler ReadWriteHandler
ServerStopChan <-chan struct{}
ServerStopWg *sync.WaitGroup
}
func (srwch *ServerRWCHandler) ConnectionSize() int {
var sz int
srwch.connections.Range(func(k, v interface{}) bool {
sz++
return true
})
return sz
}
func (srwch *ServerRWCHandler) HandleConnection(servlet Servlet, servletCtx ServletCtx, conn *Conn) {
addr := conn.RemoteAddr()
defer func() {
if nil != conn {
conn.Close()
}
servlet.OnDisconnect(servletCtx)
logging.Logger().Infof("Client[%s] has been disconnected", addr)
srwch.ServerStopWg.Done()
}()
logging.Logger().Infof("Client[%s] has been connected", addr)
srwch.connections.Store(conn, true)
defer srwch.connections.Delete(conn)
servlet.OnConnect(servletCtx, conn)
conn.SetCloseHandler(func(code int, text string) error {
logging.Logger().Debugf("close")
return nil
})
stopChan := make(chan struct{})
servletDoneChan := make(chan struct{})
readChan := make(chan []byte)
writeChan := make(chan []byte)
readerDoneChan := make(chan error)
writerDoneChan := make(chan error)
go servlet.Handle(servletCtx, stopChan, servletDoneChan, readChan, writeChan)
go connReadHandler(srwch.ReadwriteHandler, conn, stopChan, readerDoneChan, readChan)
go connWriteHandler(srwch.ReadwriteHandler, conn, stopChan, writerDoneChan, writeChan)
select {
case <-readerDoneChan:
close(stopChan)
<-writerDoneChan
<-servletDoneChan
case <-writerDoneChan:
close(stopChan)
<-readerDoneChan
<-servletDoneChan
case <-servletDoneChan:
close(stopChan)
<-readerDoneChan
<-writerDoneChan
case <-srwch.ServerStopChan:
close(stopChan)
<-readerDoneChan
<-writerDoneChan
<-servletDoneChan
}
}