From a2aab652a9eaa1271433b3712362b49e76c27297 Mon Sep 17 00:00:00 2001 From: Mickael Remond Date: Wed, 17 Feb 2016 13:45:39 +0100 Subject: [PATCH] Support connection timeout and retries --- xmpp/client.go | 17 ++++++++++++++++- xmpp/options.go | 14 ++++++++------ xmpp/parser.go | 2 +- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/xmpp/client.go b/xmpp/client.go index 3a29c39..7d9fda9 100644 --- a/xmpp/client.go +++ b/xmpp/client.go @@ -7,6 +7,7 @@ import ( "fmt" "net" "strings" + "time" ) // Client is the main structure use to connect as a client on an XMPP @@ -47,6 +48,9 @@ func NewClient(options Options) (c *Client, err error) { return } + if c.options.ConnectTimeout == 0 { + c.options.ConnectTimeout = 15 // 15 second as default + } return } @@ -71,10 +75,21 @@ func checkAddress(addr string) (string, error) { func (c *Client) Connect() (*Session, error) { var tcpconn net.Conn var err error - if tcpconn, err = net.Dial("tcp", c.options.Address); err != nil { + + // TODO: Refactor = abstract retry loop in capped exponential back-off function + var try = 0 + var success bool + for try <= c.options.Retry || !success { + if tcpconn, err = net.DialTimeout("tcp", c.options.Address, time.Duration(c.options.ConnectTimeout)*time.Second); err == nil { + success = true + } + try++ + } + if err != nil { return nil, err } + // Connection is ok, we now open XMPP session c.conn = tcpconn if c.conn, c.Session, err = NewSession(c.conn, c.options); err != nil { return c.Session, err diff --git a/xmpp/options.go b/xmpp/options.go index 96bafe6..3051511 100644 --- a/xmpp/options.go +++ b/xmpp/options.go @@ -3,10 +3,12 @@ package xmpp import "os" type Options struct { - Address string - Jid string - parsedJid *Jid // For easier manipulation - Password string - PacketLogger *os.File // Used for debugging - Lang string // TODO: should default to 'en' + Address string + Jid string + parsedJid *Jid // For easier manipulation + Password string + PacketLogger *os.File // Used for debugging + Lang string // TODO: should default to 'en' + Retry int // Number of retries for connect + ConnectTimeout int // Connection timeout in seconds. Default to 15 } diff --git a/xmpp/parser.go b/xmpp/parser.go index e625142..58c689a 100644 --- a/xmpp/parser.go +++ b/xmpp/parser.go @@ -80,7 +80,7 @@ func next(p *xml.Decoder) (xml.Name, interface{}, error) { case nsClient + " message": nv = &ClientMessage{} case nsClient + " presence": - nv = &clientPresence{} + nv = &ClientPresence{} case nsClient + " iq": nv = &ClientIQ{} default: