server/server_handlers.go
crusader 4163705d49 ing
2017-10-27 16:07:14 +09:00

83 lines
1.9 KiB
Go

package server
import (
"errors"
"io"
"net"
"time"
)
type ServerHandlers struct {
// Address to listen to for incoming connections.
//
// The address format depends on the underlying transport provided
// by Server.Listener. The following transports are provided
// out of the box:
// * TCP - see NewTCPServer() and NewTCPClient().
// * TLS (aka SSL) - see NewTLSServer() and NewTLSClient().
// * Unix sockets - see NewUnixServer() and NewUnixClient().
//
// By default TCP transport is used.
Addr string
KeepAlivePeriod time.Duration
}
func (sh *ServerHandlers) Listen() (net.Listener, error) {
return nil, errors.New("Server: Handler method[Listen] of Server is not implement")
}
func (sh *ServerHandlers) Handle(remoteAddr string, rwc io.ReadWriteCloser, stopChan chan struct{}) {
}
func (sh *ServerHandlers) IsClientDisconnect(err error) bool {
return err == io.ErrUnexpectedEOF || err == io.EOF
}
func (sh *ServerHandlers) OnStopped() {
}
func (sh *ServerHandlers) GetAddr() string {
return sh.Addr
}
func (sh *ServerHandlers) accept(l net.Listener) (io.ReadWriteCloser, string, error) {
conn, err := l.Accept()
if nil != err {
return nil, "", err
}
if 0 < sh.KeepAlivePeriod {
if err = setupKeepalive(conn, sh.KeepAlivePeriod); nil != err {
conn.Close()
return nil, "", err
}
}
return conn, conn.RemoteAddr().String(), nil
}
func (sh *ServerHandlers) Validate() {
if sh.KeepAlivePeriod <= 0 {
sh.KeepAlivePeriod = DefaultKeepAlivePeriod
}
}
func setupKeepalive(conn net.Conn, keepAlivePeriod time.Duration) error {
tcpConn, ok := conn.(*net.TCPConn)
if !ok {
return errors.New("Server: Keepalive is valid when connection is net.TCPConn")
}
if err := tcpConn.SetKeepAlive(true); err != nil {
return err
}
if err := tcpConn.SetKeepAlivePeriod(keepAlivePeriod * time.Second); err != nil {
return err
}
return nil
}