server/socket.go

73 lines
1.0 KiB
Go
Raw 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
}
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)
}