Daniel D'Souza
Daniel D'Souza

Reputation: 77

writing a client over websocket in golang

I'm writing an client that dials a websocket, and waits to receive information. I can successfully dial the websocket, but I cannot figure out how to implement some kind of asynchronous callback using the "golang.org/x/net/websocket" package. Is this even possible, or should I use the Gorilla package?

Upvotes: 1

Views: 1061

Answers (1)

Thundercat
Thundercat

Reputation: 121199

Use a for loop to read a websocket using the Gorilla package:

for {
    _, message, err := c.ReadMessage()
    if err != nil {
        log.Println("read:", err)
        c.Close()
        break
    }
    handleMessage(message)
}

Run the loop in a goroutine to make it asynchronous:

go func() {
    for {
        _, message, err := c.ReadMessage()
        if err != nil {
            log.Println("read:", err)
            c.Close()
            break
        }
        handleMessage(message)
    }
}()

Upvotes: 1

Related Questions