mirror of https://github.com/gorilla/websocket.git
Coalesce outbound messages in chat example
This commit is contained in:
parent
3ddc984058
commit
a68708917c
|
@ -5,10 +5,12 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gorilla/websocket"
|
"bytes"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
@ -25,6 +27,11 @@ const (
|
||||||
maxMessageSize = 512
|
maxMessageSize = 512
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
newline = []byte{'\n'}
|
||||||
|
space = []byte{' '}
|
||||||
|
)
|
||||||
|
|
||||||
var upgrader = websocket.Upgrader{
|
var upgrader = websocket.Upgrader{
|
||||||
ReadBufferSize: 1024,
|
ReadBufferSize: 1024,
|
||||||
WriteBufferSize: 1024,
|
WriteBufferSize: 1024,
|
||||||
|
@ -56,6 +63,7 @@ func (c *Conn) readPump() {
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
|
||||||
hub.broadcast <- message
|
hub.broadcast <- message
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -77,10 +85,26 @@ func (c *Conn) writePump() {
|
||||||
select {
|
select {
|
||||||
case message, ok := <-c.send:
|
case message, ok := <-c.send:
|
||||||
if !ok {
|
if !ok {
|
||||||
|
// The hub closed the channel.
|
||||||
c.write(websocket.CloseMessage, []byte{})
|
c.write(websocket.CloseMessage, []byte{})
|
||||||
return
|
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
|
return
|
||||||
}
|
}
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
|
|
|
@ -36,7 +36,10 @@ $(function () {
|
||||||
appendLog($("<div><b>Connection closed.</b></div>"));
|
appendLog($("<div><b>Connection closed.</b></div>"));
|
||||||
};
|
};
|
||||||
conn.onmessage = function (evt) {
|
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 {
|
} else {
|
||||||
appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"));
|
appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"));
|
||||||
|
|
Loading…
Reference in New Issue