Coalesce outbound messages in chat example

This commit is contained in:
Gary Burd 2016-06-06 16:20:22 -07:00
parent 3ddc984058
commit a68708917c
2 changed files with 30 additions and 3 deletions

View File

@ -5,10 +5,12 @@
package main
import (
"github.com/gorilla/websocket"
"bytes"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
const (
@ -25,6 +27,11 @@ const (
maxMessageSize = 512
)
var (
newline = []byte{'\n'}
space = []byte{' '}
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
@ -56,6 +63,7 @@ func (c *Conn) readPump() {
}
break
}
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
hub.broadcast <- message
}
}
@ -77,10 +85,26 @@ func (c *Conn) writePump() {
select {
case message, ok := <-c.send:
if !ok {
// The hub closed the channel.
c.write(websocket.CloseMessage, []byte{})
return
}
if err := c.write(websocket.TextMessage, message); err != nil {
c.ws.SetWriteDeadline(time.Now().Add(writeWait))
w, err := c.ws.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(message)
// Add queued chat messages to the current websocket message.
n := len(c.send)
for i := 0; i < n; i++ {
w.Write(newline)
w.Write(<-c.send)
}
if err := w.Close(); err != nil {
return
}
case <-ticker.C:

View File

@ -36,7 +36,10 @@ $(function () {
appendLog($("<div><b>Connection closed.</b></div>"));
};
conn.onmessage = function (evt) {
appendLog($("<div/>").text(evt.data));
var messages = evt.data.split('\n')
for (var i = 0; i < messages.length; i++) {
appendLog($("<div/>").text(messages[i]));
}
};
} else {
appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"));