1
0

client.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. }
  30. // Client is a middleman between the websocket connection and the hub.
  31. type Client struct {
  32. hub *Hub
  33. // The websocket connection.
  34. conn *websocket.Conn
  35. // Buffered channel of outbound messages.
  36. send chan []byte
  37. }
  38. // readPump pumps messages from the websocket connection to the hub.
  39. //
  40. // The application runs readPump in a per-connection goroutine. The application
  41. // ensures that there is at most one reader on a connection by executing all
  42. // reads from this goroutine.
  43. func (c *Client) readPump() {
  44. defer func() {
  45. c.hub.unregister <- c
  46. c.conn.Close()
  47. }()
  48. c.conn.SetReadLimit(maxMessageSize)
  49. c.conn.SetReadDeadline(time.Now().Add(pongWait))
  50. c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
  51. for {
  52. _, message, err := c.conn.ReadMessage()
  53. if err != nil {
  54. if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
  55. log.Printf("error: %v", err)
  56. }
  57. break
  58. }
  59. message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
  60. c.hub.broadcast <- message
  61. }
  62. }
  63. // writePump pumps messages from the hub to the websocket connection.
  64. //
  65. // A goroutine running writePump is started for each connection. The
  66. // application ensures that there is at most one writer to a connection by
  67. // executing all writes from this goroutine.
  68. func (c *Client) writePump() {
  69. ticker := time.NewTicker(pingPeriod)
  70. defer func() {
  71. ticker.Stop()
  72. c.conn.Close()
  73. }()
  74. for {
  75. select {
  76. case message, ok := <-c.send:
  77. c.conn.SetWriteDeadline(time.Now().Add(writeWait))
  78. if !ok {
  79. // The hub closed the channel.
  80. c.conn.WriteMessage(websocket.CloseMessage, []byte{})
  81. return
  82. }
  83. w, err := c.conn.NextWriter(websocket.TextMessage)
  84. if err != nil {
  85. return
  86. }
  87. w.Write(message)
  88. // Add queued chat messages to the current websocket message.
  89. n := len(c.send)
  90. for i := 0; i < n; i++ {
  91. w.Write(newline)
  92. w.Write(<-c.send)
  93. }
  94. if err := w.Close(); err != nil {
  95. return
  96. }
  97. case <-ticker.C:
  98. c.conn.SetWriteDeadline(time.Now().Add(writeWait))
  99. if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
  100. return
  101. }
  102. }
  103. }
  104. }
  105. // serveWs handles websocket requests from the peer.
  106. func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
  107. conn, err := upgrader.Upgrade(w, r, nil)
  108. if err != nil {
  109. log.Println(err)
  110. return
  111. }
  112. client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}
  113. client.hub.register <- client
  114. // Allow collection of memory referenced by the caller by doing all work in
  115. // new goroutines.
  116. go client.writePump()
  117. go client.readPump()
  118. }