88 lines
1.4 KiB
Go
88 lines
1.4 KiB
Go
package server
|
|
|
|
import (
|
|
"net"
|
|
"sync"
|
|
"time"
|
|
|
|
"git.loafle.net/commons_go/logging"
|
|
)
|
|
|
|
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
|
|
|
|
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
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
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)
|
|
}
|