2017-11-30 09:13:58 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"git.loafle.net/commons_go/logging"
|
2017-11-30 09:36:59 +00:00
|
|
|
cuc "git.loafle.net/commons_go/util/context"
|
2017-11-30 09:13:58 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Socket interface {
|
|
|
|
Context() SocketContext
|
|
|
|
|
|
|
|
net.Conn
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSocket(sb SocketBuilder, parentContext cuc.Context) (Socket, error) {
|
|
|
|
if nil == sb {
|
|
|
|
logging.Logger().Panic("Client Socket: SocketBuilder must be specified")
|
|
|
|
}
|
|
|
|
sb.Validate()
|
|
|
|
|
|
|
|
sc := sb.SocketContext(parentContext)
|
|
|
|
if nil == sc {
|
|
|
|
logging.Logger().Panic("Client Socket: SocketContext must be specified")
|
|
|
|
}
|
|
|
|
|
|
|
|
sh := sb.SocketHandler()
|
|
|
|
if nil == sh {
|
|
|
|
logging.Logger().Panic("Client Socket: SocketHandler must be specified")
|
|
|
|
}
|
|
|
|
sh.Validate()
|
|
|
|
|
|
|
|
d := &net.Dialer{}
|
|
|
|
d.Timeout = sb.GetTimeout()
|
|
|
|
d.KeepAlive = sb.GetKeepAlive()
|
|
|
|
d.LocalAddr = sb.GetLocalAddress()
|
|
|
|
|
|
|
|
network := sb.GetNetwork()
|
|
|
|
address := sb.GetAddress()
|
|
|
|
|
2017-11-30 09:57:09 +00:00
|
|
|
conn, err := sb.Dial(d, network, address)
|
2017-11-30 09:13:58 +00:00
|
|
|
|
|
|
|
if nil != err {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
sh.OnConnect(sc, conn)
|
|
|
|
|
|
|
|
s := retainSocket()
|
|
|
|
s.ctx = sc
|
|
|
|
s.sh = sh
|
|
|
|
|
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type netSocket struct {
|
|
|
|
net.Conn
|
|
|
|
|
|
|
|
ctx SocketContext
|
|
|
|
sh SocketHandler
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *netSocket) Context() SocketContext {
|
|
|
|
return s.ctx
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *netSocket) Close() error {
|
|
|
|
err := s.Conn.Close()
|
|
|
|
s.sh.OnDisconnect(s)
|
|
|
|
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
|
|
|
|
|
|
|
|
socketPool.Put(s)
|
|
|
|
}
|