From 54665f160ab37ffdd5625b8b0c4e9599150f8ce6 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Tue, 14 Jun 2022 14:07:45 +1000 Subject: [PATCH] Rework peer connection writer to keep individual writes smaller This fixes an issue with WebRTC when the write buffers get too big. --- peer-conn-msg-writer.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/peer-conn-msg-writer.go b/peer-conn-msg-writer.go index 3948eb64..87ed4750 100644 --- a/peer-conn-msg-writer.go +++ b/peer-conn-msg-writer.go @@ -86,19 +86,25 @@ func (cn *peerConnMsgWriter) run(keepAliveTimeout time.Duration) { // Flip the buffers. frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf cn.mu.Unlock() - n, err := cn.w.Write(frontBuf.Bytes()) - if n != 0 { - lastWrite = time.Now() - keepAliveTimer.Reset(keepAliveTimeout) + if frontBuf.Len() == 0 { + panic("expected non-empty front buffer") + } + var err error + for frontBuf.Len() != 0 { + // Limit write size for WebRTC. See https://github.com/pion/datachannel/issues/59. + next := frontBuf.Next(1<<16 - 1) + var n int + n, err = cn.w.Write(next) + if err == nil && n != len(next) { + panic("expected full write") + } } if err != nil { cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err) return } - if n != frontBuf.Len() { - panic("short write") - } - frontBuf.Reset() + lastWrite = time.Now() + keepAliveTimer.Reset(keepAliveTimeout) } } -- 2.48.1