client.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 an 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. func (c *Client) readPump() {
  40. defer func() {
  41. c.hub.unregister <- c
  42. c.conn.Close()
  43. }()
  44. c.conn.SetReadLimit(maxMessageSize)
  45. c.conn.SetReadDeadline(time.Now().Add(pongWait))
  46. c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
  47. for {
  48. _, message, err := c.conn.ReadMessage()
  49. if err != nil {
  50. if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
  51. log.Printf("error: %v", err)
  52. }
  53. break
  54. }
  55. message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
  56. c.hub.broadcast <- message
  57. }
  58. }
  59. // write writes a message with the given message type and payload.
  60. func (c *Client) write(mt int, payload []byte) error {
  61. c.conn.SetWriteDeadline(time.Now().Add(writeWait))
  62. return c.conn.WriteMessage(mt, payload)
  63. }
  64. // writePump pumps messages from the hub to the websocket connection.
  65. func (c *Client) writePump() {
  66. ticker := time.NewTicker(pingPeriod)
  67. defer func() {
  68. ticker.Stop()
  69. c.conn.Close()
  70. }()
  71. for {
  72. select {
  73. case message, ok := <-c.send:
  74. if !ok {
  75. // The hub closed the channel.
  76. c.write(websocket.CloseMessage, []byte{})
  77. return
  78. }
  79. c.conn.SetWriteDeadline(time.Now().Add(writeWait))
  80. w, err := c.conn.NextWriter(websocket.TextMessage)
  81. if err != nil {
  82. return
  83. }
  84. w.Write(message)
  85. // Add queued chat messages to the current websocket message.
  86. n := len(c.send)
  87. for i := 0; i < n; i++ {
  88. w.Write(newline)
  89. w.Write(<-c.send)
  90. }
  91. if err := w.Close(); err != nil {
  92. return
  93. }
  94. case <-ticker.C:
  95. if err := c.write(websocket.PingMessage, []byte{}); err != nil {
  96. return
  97. }
  98. }
  99. }
  100. }
  101. // serveWs handles websocket requests from the peer.
  102. func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
  103. conn, err := upgrader.Upgrade(w, r, nil)
  104. if err != nil {
  105. log.Println(err)
  106. return
  107. }
  108. client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}
  109. client.hub.register <- client
  110. go client.writePump()
  111. client.readPump()
  112. }