Reputation: 89
I would like to see a minimal and simple example of how to connect to a websocket using gorilla.
The only example I found to connect to a websocket was this, but I couldn't understand it, and I couldn't find an explanation of how it works.
Edit:
Line 20:
Why did he keep the websocket address in flag.String
instead of a variable string?
Line 26:
Does this part create a signal that will notify the program when the user presses crtl + C?
interrupt: = make(chan os.Signal, 1)
signal.Notify (interrupt, os.Interrupt)
Line 32:
What does this line do?
websocket.DefaultDialer.Dial (u.String (), nil)
Line 60:
Because []byte(t.String())
instead of t.string()
?
Upvotes: 0
Views: 1080
Reputation: 273716
The sample's README
says:
The client sends a message every second and prints all messages received.
Looking at the code, the latter part (prints all messages received) happens here:
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
log.Printf("recv: %s", message)
}
}()
This spins up a goroutine that reads messages from c
(the websocket connection) in a loop and prints them out. It stops when the read fails, which happens for errors and when the connection is closed.
The main goroutine does this:
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-done:
return
case t := <-ticker.C:
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
log.Println("write:", err)
return
}
case <-interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
It has a ticker firing every second, on which a message is sent to the websocket. When the reader goroutine is done it closes the done
channel, which signals this loop with the select
to exit too.
Finally, there's an "interrupt" selection to handle Ctrl+C, cleanly stopping the client.
To answer your specific questions:
Line 20: this flag enables you to set the address from the command line when executing the program, instead of it being hardcoded. You can call it like client -addr localhost:9044
to set a different port, for example. See also https://gobyexample.com/command-line-flags
Line 26: yes this is for Ctrl+C
; see also https://gobyexample.com/signals
Line 32: DefaultDialer
is a preconfigured dialer in the websocket
package. Per the documentation, it's equivalent to
var DefaultDialer = &Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 45 * time.Second,
}
Line 60: WriteMessage takes a []byte
, so you have to convert the string to a []byte
Upvotes: 0