client.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // Copyright 2013 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. package main
  5. import (
  6. "bytes"
  7. "log"
  8. "net/http"
  9. "time"
  10. "github.com/gorilla/websocket"
  11. )
  12. const (
  13. // Time allowed to write a message to the peer.
  14. writeWait = 10 * time.Second
  15. // Time allowed to read the next pong message from the peer.
  16. pongWait = 60 * time.Second
  17. // Send pings to peer with this period. Must be less than pongWait.
  18. pingPeriod = (pongWait * 9) / 10
  19. // Maximum message size allowed from peer.
  20. maxMessageSize = 512
  21. )
  22. var (
  23. newline = []byte{'\n'}
  24. space = []byte{' '}
  25. )
  26. var upgrader = websocket.Upgrader{
  27. ReadBufferSize: 1024,
  28. WriteBufferSize: 1024,
  29. CheckOrigin: func(r *http.Request) bool {
  30. return true
  31. },
  32. }
  33. // Client is a middleman between the websocket connection and the hub.
  34. type Client struct {
  35. hub *Hub
  36. // The websocket connection.
  37. conn *websocket.Conn
  38. // Buffered channel of outbound messages.
  39. send chan []byte
  40. }
  41. // readPump pumps messages from the websocket connection to the hub.
  42. //
  43. // The application runs readPump in a per-connection goroutine. The application
  44. // ensures that there is at most one reader on a connection by executing all
  45. // reads from this goroutine.
  46. func (c *Client) readPump() {
  47. defer func() {
  48. c.hub.unregister <- c
  49. c.conn.Close()
  50. }()
  51. c.conn.SetReadLimit(maxMessageSize)
  52. c.conn.SetReadDeadline(time.Now().Add(pongWait))
  53. c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
  54. for {
  55. _, message, err := c.conn.ReadMessage()
  56. if err != nil {
  57. if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
  58. log.Printf("error: %v", err)
  59. }
  60. break
  61. }
  62. message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
  63. c.hub.broadcast <- message
  64. }
  65. }
  66. // writePump pumps messages from the hub to the websocket connection.
  67. //
  68. // A goroutine running writePump is started for each connection. The
  69. // application ensures that there is at most one writer to a connection by
  70. // executing all writes from this goroutine.
  71. func (c *Client) writePump() {
  72. ticker := time.NewTicker(pingPeriod)
  73. defer func() {
  74. ticker.Stop()
  75. c.conn.Close()
  76. }()
  77. for {
  78. select {
  79. case message, ok := <-c.send:
  80. c.conn.SetWriteDeadline(time.Now().Add(writeWait))
  81. if !ok {
  82. // The hub closed the channel.
  83. c.conn.WriteMessage(websocket.CloseMessage, []byte{})
  84. return
  85. }
  86. w, err := c.conn.NextWriter(websocket.TextMessage)
  87. if err != nil {
  88. return
  89. }
  90. w.Write(message)
  91. // Add queued chat messages to the current websocket message.
  92. n := len(c.send)
  93. for i := 0; i < n; i++ {
  94. w.Write(newline)
  95. w.Write(<-c.send)
  96. }
  97. if err := w.Close(); err != nil {
  98. return
  99. }
  100. case <-ticker.C:
  101. c.conn.SetWriteDeadline(time.Now().Add(writeWait))
  102. if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
  103. return
  104. }
  105. }
  106. }
  107. }
  108. // serveWs handles websocket requests from the peer.
  109. func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
  110. conn, err := upgrader.Upgrade(w, r, nil)
  111. if err != nil {
  112. log.Println(err)
  113. return
  114. }
  115. client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}
  116. client.hub.register <- client
  117. // Allow collection of memory referenced by the caller by doing all work in
  118. // new goroutines.
  119. go client.writePump()
  120. go client.readPump()
  121. }