websocket/examples/echo/client.go

84 lines
1.6 KiB
Go
Raw Normal View History

2015-09-24 01:29:30 +03:00
// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
2015-09-24 01:23:26 +03:00
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
2015-09-24 01:29:30 +03:00
// +build ignore
2015-09-24 01:23:26 +03:00
package main
import (
"flag"
"log"
"net/url"
"os"
"os/signal"
2015-09-24 01:23:26 +03:00
"time"
"github.com/gorilla/websocket"
)
2015-11-02 21:39:51 +03:00
var addr = flag.String("addr", "localhost:8080", "http service address")
2015-09-24 01:23:26 +03:00
func main() {
flag.Parse()
log.SetFlags(0)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
2015-11-02 21:39:51 +03:00
u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"}
2015-09-24 01:23:26 +03:00
log.Printf("connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
2015-09-24 01:23:26 +03:00
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
2015-09-24 01:23:26 +03:00
go func() {
defer close(done)
2015-09-24 01:23:26 +03:00
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
2015-09-24 01:23:26 +03:00
}
log.Printf("recv: %s", message)
}
}()
2015-11-02 21:39:51 +03:00
ticker := time.NewTicker(time.Second)
2015-09-24 01:23:26 +03:00
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
2015-09-24 01:23:26 +03:00
}
}
}