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.
13 "github.com/gorilla/websocket"
17 // Time allowed to write a message to the peer.
18 writeWait = 10 * time.Second
20 // Time allowed to read the next pong message from the peer.
21 pongWait = 60 * time.Second
23 // Send pings to peer with this period. Must be less than pongWait.
24 pingPeriod = (pongWait * 9) / 10
26 // Maximum message size allowed from peer.
31 newline = []byte{'\n'}
35 var upgrader = websocket.Upgrader{
37 WriteBufferSize: 1024,
40 // Client is a middleman between the websocket connection and the hub.
44 // The websocket connection.
47 // Buffered channel of outbound messages.
51 // readPump pumps messages from the websocket connection to the hub.
53 // The application runs readPump in a per-connection goroutine. The application
54 // ensures that there is at most one reader on a connection by executing all
55 // reads from this goroutine.
56 func (c *Client) readPump() {
61 c.conn.SetReadLimit(maxMessageSize)
62 c.conn.SetReadDeadline(time.Now().Add(pongWait))
63 c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
65 _, message, err := c.conn.ReadMessage()
67 if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
68 log.Printf("error: %v", err)
72 message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
73 c.hub.broadcast <- message
77 // writePump pumps messages from the hub to the websocket connection.
79 // A goroutine running writePump is started for each connection. The
80 // application ensures that there is at most one writer to a connection by
81 // executing all writes from this goroutine.
82 func (c *Client) writePump() {
83 ticker := time.NewTicker(pingPeriod)
90 case message, ok := <-c.send:
91 c.conn.SetWriteDeadline(time.Now().Add(writeWait))
93 // The hub closed the channel.
94 c.conn.WriteMessage(websocket.CloseMessage, []byte{})
98 w, err := c.conn.NextWriter(websocket.TextMessage)
104 // Add queued chat messages to the current websocket message.
106 for i := 0; i < n; i++ {
111 if err := w.Close(); err != nil {
115 c.conn.SetWriteDeadline(time.Now().Add(writeWait))
116 if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
123 // serveWs handles websocket requests from the peer.
124 func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
125 conn, err := upgrader.Upgrade(w, r, nil)
130 client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}
131 client.hub.register <- client
133 // Allow collection of memory referenced by the caller by doing all work in
135 go client.writePump()