conn.go 2.9 KB

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