2017-10-26 11:14:00 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2017-10-27 08:53:26 +00:00
|
|
|
func (sh *ServerHandlers) OnStart() {
|
|
|
|
// no op
|
|
|
|
}
|
|
|
|
|
|
|
|
func (sh *ServerHandlers) OnStop() {
|
|
|
|
// no op
|
|
|
|
}
|
|
|
|
|
2017-10-26 11:14:00 +00:00
|
|
|
func (sh *ServerHandlers) Listen() (net.Listener, error) {
|
|
|
|
return nil, errors.New("Server: Handler method[Listen] of Server is not implement")
|
|
|
|
}
|
|
|
|
|
2017-10-27 07:14:20 +00:00
|
|
|
func (sh *ServerHandlers) OnHandshake(remoteAddr string, rwc io.ReadWriteCloser) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-10-26 11:14:00 +00:00
|
|
|
func (sh *ServerHandlers) Handle(remoteAddr string, rwc io.ReadWriteCloser, stopChan chan struct{}) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2017-10-27 05:27:36 +00:00
|
|
|
func (sh *ServerHandlers) IsClientDisconnect(err error) bool {
|
|
|
|
return err == io.ErrUnexpectedEOF || err == io.EOF
|
|
|
|
}
|
|
|
|
|
2017-10-26 12:08:50 +00:00
|
|
|
func (sh *ServerHandlers) GetAddr() string {
|
|
|
|
return sh.Addr
|
2017-10-26 11:14:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|