server/socket.go

86 lines
1.4 KiB
Go
Raw Permalink Normal View History

2017-11-29 00:51:41 +00:00
package server
import (
"net"
"sync"
"time"
)
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)
2018-03-23 03:27:41 +00:00
// logging.Logger().Debugf("Server Socket: read message[%s]", string(b))
2018-03-22 14:17:20 +00:00
return
}
func (s *netSocket) Write(b []byte) (n int, err error) {
2018-03-23 03:27:41 +00:00
// logging.Logger().Debugf("Server Socket: write message[%s]", string(b))
2018-03-22 14:17:20 +00:00
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)
}