diff --git a/client.go b/client.go index 38063a0..4de2d43 100644 --- a/client.go +++ b/client.go @@ -127,7 +127,7 @@ func startClient(conn *websocket.Conn) (err error) { defer close(c.done) - c.writeCh = make(chan interface{}, 1) + c.writeCh = make(chan interface{}, 25) defer func() { if isWSNormalError(err) { err = nil @@ -693,6 +693,20 @@ func clientLoop(c *client, conn *websocket.Conn) error { cc.action(pushTracksAction{c}) } + h := c.group.getChatHistory() + for _, m := range h { + err := c.write(clientMessage{ + Type: "chat", + Id: m.id, + Username: m.user, + Value: m.value, + Me: m.me, + }) + if err != nil { + return err + } + } + ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() @@ -819,6 +833,7 @@ func handleClientMessage(c *client, m clientMessage) error { log.Printf("ICE: %v", err) } case "chat": + c.group.addToChatHistory(m.Id, m.Username, m.Value, m.Me) clients := c.group.getClients(c) for _, cc := range clients { cc.write(m) diff --git a/group.go b/group.go index 72821d6..6b8f6ee 100644 --- a/group.go +++ b/group.go @@ -51,6 +51,13 @@ type client struct { up map[string]*upConnection } +type chatHistoryEntry struct { + id string + user string + value string + me bool +} + type group struct { name string dead bool @@ -58,6 +65,7 @@ type group struct { mu sync.Mutex clients []*client + history []chatHistoryEntry } type delPCAction struct { @@ -259,6 +267,30 @@ func (g *group) Range(f func(c *client) bool) { } } +const maxChatHistory = 20 + +func (g *group) addToChatHistory(id, user, value string, me bool) { + g.mu.Lock() + defer g.mu.Unlock() + + if len(g.history) >= maxChatHistory { + copy(g.history, g.history[1:]) + g.history = g.history[:len(g.history)-1] + } + g.history = append(g.history, + chatHistoryEntry{id: id, user: user, value: value, me: me}, + ) +} + +func (g *group) getChatHistory() []chatHistoryEntry { + g.mu.Lock() + g.mu.Unlock() + + h := make([]chatHistoryEntry, len(g.history)) + copy(h, g.history) + return h +} + type writerDeadError int func (err writerDeadError) Error() string { diff --git a/static/sfu.js b/static/sfu.js index 3b93655..5ff7457 100644 --- a/static/sfu.js +++ b/static/sfu.js @@ -283,6 +283,7 @@ function serverConnect() { }; socket.onopen = function(e) { resetUsers(); + resetChat(); setConnected(true); let up = getUserPass(); send({ @@ -648,6 +649,11 @@ function addToChatbox(peerId, nick, message, me){ return message; } +function resetChat() { + lastMessage = {}; + document.getElementById('box').textContent = ''; +} + function handleInput() { let username = getUsername(); let input = document.getElementById('input'); @@ -729,6 +735,7 @@ function handleInput() { addToChatbox(myid, username, message, me); send({ type: 'chat', + id: myid, username: username, value: message, me: me,