server/client.go

129 lines
2.1 KiB
Go
Raw Normal View History

2017-10-27 07:07:14 +00:00
package server
import (
"fmt"
"io"
"sync"
"sync/atomic"
"time"
"git.loafle.net/commons_go/logging"
)
type Client interface {
2017-10-31 10:55:21 +00:00
Start()
2017-10-27 07:07:14 +00:00
Stop()
}
func NewClient(ch ClientHandler) Client {
s := &client{
2017-10-31 10:46:32 +00:00
ch: ch,
2017-10-27 07:07:14 +00:00
}
return s
}
type client struct {
2017-10-31 10:46:32 +00:00
ch ClientHandler
2017-10-27 07:07:14 +00:00
Stats ConnStats
stopChan chan struct{}
stopWg sync.WaitGroup
}
2017-10-31 10:55:21 +00:00
func (c *client) Start() {
2017-10-31 10:46:32 +00:00
if nil == c.ch {
2017-10-27 07:07:14 +00:00
panic("Client: client handler must be specified.")
}
2017-10-31 10:46:32 +00:00
c.ch.Validate()
2017-10-27 07:07:14 +00:00
if c.stopChan != nil {
panic("Client: client is already running. Stop it before starting it again")
}
c.stopChan = make(chan struct{})
2017-10-31 10:46:32 +00:00
c.ch.OnStart()
2017-10-27 08:53:26 +00:00
2017-10-27 07:07:14 +00:00
c.stopWg.Add(1)
go runClient(c)
}
func (c *client) Stop() {
if c.stopChan == nil {
panic("Client: client must be started before stopping it")
}
close(c.stopChan)
c.stopWg.Wait()
c.stopChan = nil
2017-10-31 10:46:32 +00:00
c.ch.OnStop()
2017-10-27 07:07:14 +00:00
}
func runClient(c *client) {
defer c.stopWg.Done()
var conn io.ReadWriteCloser
var err error
var stopping atomic.Value
for {
dialChan := make(chan struct{})
go func() {
2017-10-31 10:46:32 +00:00
if conn, err = c.ch.Dial(); err != nil {
2017-10-27 07:07:14 +00:00
if stopping.Load() == nil {
2017-10-31 10:46:32 +00:00
logging.Logger.Error(fmt.Sprintf("Client: [%s].Cannot establish rpc connection: [%s]", c.ch.GetAddr(), err))
2017-10-27 07:07:14 +00:00
}
}
close(dialChan)
}()
select {
case <-c.stopChan:
stopping.Store(true)
<-dialChan
return
case <-dialChan:
c.Stats.incDialCalls()
}
if err != nil {
c.Stats.incDialErrors()
select {
case <-c.stopChan:
return
case <-time.After(time.Second):
}
continue
}
c.stopWg.Add(1)
handleClientConnection(c, conn)
select {
case <-c.stopChan:
return
default:
}
}
}
func handleClientConnection(c *client, conn io.ReadWriteCloser) {
2017-10-31 10:46:32 +00:00
if err := c.ch.OnHandshake(c.ch.GetAddr(), conn); nil != err {
logging.Logger.Error(fmt.Sprintf("Client: [%s]. handshake error: [%s]", c.ch.GetAddr(), err))
2017-10-27 07:07:14 +00:00
conn.Close()
return
}
clientStopChan := make(chan struct{})
2017-10-31 10:46:32 +00:00
go c.ch.Handle(conn, clientStopChan)
2017-10-27 07:07:14 +00:00
select {
case <-c.stopChan:
close(clientStopChan)
conn.Close()
return
case <-clientStopChan:
conn.Close()
return
}
}