Browse Source

make WSClient thread-safe

pull/604/head
Anton Kaliaev 7 years ago
parent
commit
57eee2466b
No known key found for this signature in database GPG Key ID: 7B6881D965918214
1 changed files with 12 additions and 3 deletions
  1. +12
    -3
      rpc/lib/client/ws_client.go

+ 12
- 3
rpc/lib/client/ws_client.go View File

@ -29,6 +29,8 @@ const (
defaultPingPeriod = (defaultPongWait * 9) / 10 defaultPingPeriod = (defaultPongWait * 9) / 10
) )
// WSClient is a WebSocket client. The methods of WSClient are safe for use by
// multiple goroutines.
type WSClient struct { type WSClient struct {
cmn.BaseService cmn.BaseService
@ -50,12 +52,11 @@ type WSClient struct {
reconnectAfter chan error // reconnect requests reconnectAfter chan error // reconnect requests
readRoutineQuit chan struct{} // a way for readRoutine to close writeRoutine readRoutineQuit chan struct{} // a way for readRoutine to close writeRoutine
reconnecting bool
wg sync.WaitGroup wg sync.WaitGroup
mtx sync.RWMutex mtx sync.RWMutex
sentLastPingAt time.Time sentLastPingAt time.Time
reconnecting bool
// Time allowed to read the next pong message from the server. // Time allowed to read the next pong message from the server.
pongWait time.Duration pongWait time.Duration
@ -64,7 +65,9 @@ type WSClient struct {
pingPeriod time.Duration pingPeriod time.Duration
} }
// NewWSClient returns a new client.
// NewWSClient returns a new client. See the commentary on the func(*WSClient)
// functions for a detailed description of how to configure ping period and
// pong wait time.
func NewWSClient(remoteAddr, endpoint string, options ...func(*WSClient)) *WSClient { func NewWSClient(remoteAddr, endpoint string, options ...func(*WSClient)) *WSClient {
addr, dialer := makeHTTPDialer(remoteAddr) addr, dialer := makeHTTPDialer(remoteAddr)
c := &WSClient{ c := &WSClient{
@ -140,6 +143,8 @@ func (c *WSClient) Stop() bool {
// IsReconnecting returns true if the client is reconnecting right now. // IsReconnecting returns true if the client is reconnecting right now.
func (c *WSClient) IsReconnecting() bool { func (c *WSClient) IsReconnecting() bool {
c.mtx.RLock()
defer c.mtx.RUnlock()
return c.reconnecting return c.reconnecting
} }
@ -202,9 +207,13 @@ func (c *WSClient) dial() error {
func (c *WSClient) reconnect() error { func (c *WSClient) reconnect() error {
attempt := 0 attempt := 0
c.mtx.Lock()
c.reconnecting = true c.reconnecting = true
c.mtx.Unlock()
defer func() { defer func() {
c.mtx.Lock()
c.reconnecting = false c.reconnecting = false
c.mtx.Unlock()
}() }()
for { for {


Loading…
Cancel
Save