From 86dba9aa0ba974ef56bd246964703d8ef82e5ab0 Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Sun, 6 May 2018 01:05:38 +0200 Subject: [PATCH] chunk message writer --- ws/message.go | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/ws/message.go b/ws/message.go index 006644b..a2f6e2d 100644 --- a/ws/message.go +++ b/ws/message.go @@ -10,6 +10,7 @@ var UnmaskedFrameErr = fmt.Errorf("Received unmasked frame") // Maximum Header Size = Final/OpCode + isMask/Length + Length + Mask const maximumHeaderSize = 1 + 1 + 8 + 4 +const maxWriteChunk = 0x7fff // Lists websocket close status type MessageError uint16 @@ -28,12 +29,12 @@ const ( type MessageType byte const ( - CONTINUATION MessageType = 0x0 - TEXT MessageType = 0x1 - BINARY MessageType = 0x2 - CLOSE MessageType = 0x8 - PING MessageType = 0x9 - PONG MessageType = 0xa + CONTINUATION MessageType = 0x00 + TEXT MessageType = 0x01 + BINARY MessageType = 0x02 + CLOSE MessageType = 0x08 + PING MessageType = 0x09 + PONG MessageType = 0x0a ); @@ -200,9 +201,24 @@ func (m Message) Send(writer io.Writer) error { writeBuf = append(writeBuf, header...) writeBuf = append(writeBuf, m.Data[0:m.Size]...) - /* (4) Send over socket */ - _, err := writer.Write(writeBuf) - if err != nil { return err } + /* (4) Send over socket by chunks */ + toWrite := len(header) + int(m.Size) + cursor := 0 + for cursor < toWrite { + + maxBoundary := cursor+maxWriteChunk + if maxBoundary > toWrite { + maxBoundary = toWrite + } + + // Try to wrote (at max 1024 bytes) // + nbwritten, err := writer.Write(writeBuf[cursor:maxBoundary]) + if err != nil { return err } + + // Update cursor // + cursor += nbwritten + + } return nil } \ No newline at end of file