client.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build ignore
  5. package main
  6. import (
  7. "flag"
  8. "log"
  9. "net/url"
  10. "os"
  11. "os/signal"
  12. "time"
  13. "github.com/gorilla/websocket"
  14. )
  15. var addr = flag.String("addr", "localhost:8080", "http service address")
  16. func main() {
  17. flag.Parse()
  18. log.SetFlags(0)
  19. interrupt := make(chan os.Signal, 1)
  20. signal.Notify(interrupt, os.Interrupt)
  21. u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"}
  22. log.Printf("connecting to %s", u.String())
  23. c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
  24. if err != nil {
  25. log.Fatal("dial:", err)
  26. }
  27. defer c.Close()
  28. done := make(chan struct{})
  29. go func() {
  30. defer c.Close()
  31. defer close(done)
  32. for {
  33. _, message, err := c.ReadMessage()
  34. if err != nil {
  35. log.Println("read:", err)
  36. return
  37. }
  38. log.Printf("recv: %s", message)
  39. }
  40. }()
  41. ticker := time.NewTicker(time.Second)
  42. defer ticker.Stop()
  43. for {
  44. select {
  45. case t := <-ticker.C:
  46. err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
  47. if err != nil {
  48. log.Println("write:", err)
  49. return
  50. }
  51. case <-interrupt:
  52. log.Println("interrupt")
  53. // To cleanly close a connection, a client should send a close
  54. // frame and wait for the server to close the connection.
  55. err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  56. if err != nil {
  57. log.Println("write close:", err)
  58. return
  59. }
  60. select {
  61. case <-done:
  62. case <-time.After(time.Second):
  63. }
  64. c.Close()
  65. return
  66. }
  67. }
  68. }