2017-11-29 00:51:41 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
"time"
|
2018-03-22 14:17:20 +00:00
|
|
|
|
|
|
|
"git.loafle.net/commons_go/logging"
|
2017-11-29 00:51:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Socket interface {
|
|
|
|
// ID returns the identity of the client.
|
|
|
|
ID() string
|
|
|
|
Context() SocketContext
|
|
|
|
|
|
|
|
net.Conn
|
|
|
|
}
|
|
|
|
|
|
|
|
func newSocket(socketHandler SocketHandler, socketCTX SocketContext, conn net.Conn, id string) Socket {
|
|
|
|
s := retainSocket()
|
|
|
|
s.Conn = conn
|
|
|
|
s.sh = socketHandler
|
|
|
|
s.id = id
|
2017-11-29 03:46:40 +00:00
|
|
|
|
2017-11-29 00:51:41 +00:00
|
|
|
if 0 < socketHandler.GetReadTimeout() {
|
|
|
|
s.SetReadDeadline(time.Now().Add(socketHandler.GetReadTimeout() * time.Second))
|
|
|
|
}
|
|
|
|
s.ctx = socketCTX
|
|
|
|
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
type netSocket struct {
|
|
|
|
net.Conn
|
|
|
|
|
|
|
|
ctx SocketContext
|
|
|
|
sh SocketHandler
|
|
|
|
|
|
|
|
id string
|
|
|
|
|
|
|
|
// sc *SocketConn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *netSocket) Context() SocketContext {
|
|
|
|
return s.ctx
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *netSocket) ID() string {
|
|
|
|
return s.id
|
|
|
|
}
|
|
|
|
|
2018-03-22 14:17:20 +00:00
|
|
|
func (s *netSocket) Read(b []byte) (n int, err error) {
|
|
|
|
n, err = s.Conn.Read(b)
|
|
|
|
|
|
|
|
logging.Logger().Debugf("Server Socket: read message[%s]", string(b))
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *netSocket) Write(b []byte) (n int, err error) {
|
|
|
|
logging.Logger().Debugf("Server Socket: write message[%s]", string(b))
|
|
|
|
return s.Conn.Write(b)
|
|
|
|
}
|
|
|
|
|
2017-11-29 00:51:41 +00:00
|
|
|
func (s *netSocket) Close() error {
|
|
|
|
err := s.Conn.Close()
|
|
|
|
releaseSocket(s)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
var socketPool sync.Pool
|
|
|
|
|
|
|
|
func retainSocket() *netSocket {
|
|
|
|
v := socketPool.Get()
|
|
|
|
if v == nil {
|
|
|
|
return &netSocket{}
|
|
|
|
}
|
|
|
|
return v.(*netSocket)
|
|
|
|
}
|
|
|
|
|
|
|
|
func releaseSocket(s *netSocket) {
|
|
|
|
s.sh = nil
|
|
|
|
s.ctx = nil
|
|
|
|
s.id = ""
|
|
|
|
|
|
|
|
socketPool.Put(s)
|
|
|
|
}
|