jcelliott / turnpike

Go implementation of a WAMP (Web Application Messaging Protocol) client and router
MIT License
258 stars 88 forks source link

Best way to implement reconnect #141

Open utdrmac opened 7 years ago

utdrmac commented 7 years ago

I frequently get "Unable to connect: Failed handshake" from the service to which I'm attempting connections. What's the best way to handle auto-rety/auto-reconnect? Right now I have this (I'm not the best Go programmer)

var c *turnpike.Client
    var err error

    for {
        c, err = turnpike.NewWebsocketClient(turnpike.JSON, WEBSOCKET_ADDRESS, nil, nil, nil)
        if err != nil {
            log.Printf("Unable to connect to Websocket. Error: %s\n", err)

            // Retry in 5 seconds
            time.Sleep(5)

            continue
        }

        log.Println("Connected to Websocket.")

        _, err = c.JoinRealm(WEBSOCKET_REALM, nil)
        if err != nil {
            log.Printf("Unable to join realm. Error: %s\n", err)
            c.Close()

            // Retry in 5 seconds
            time.Sleep(5)

            continue
        }

        log.Println("Joined Websocket realm.")

        // No errs; break loop
        break
    }

       // have successful connection and successful join realm
       // continue code