From 92d350fe88d4c3604f4a605bdef18de1902d1ab6 Mon Sep 17 00:00:00 2001 From: Tanguy Date: Thu, 30 Jun 2022 17:14:07 +0200 Subject: [PATCH] Fix fragmented message sending (#116) We previously crashed when sending things over 1mb --- tests/testwebsockets.nim | 4 ++-- websock/session.nim | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/testwebsockets.nim b/tests/testwebsockets.nim index 40c9d641..0a15d5aa 100644 --- a/tests/testwebsockets.nim +++ b/tests/testwebsockets.nim @@ -783,11 +783,11 @@ suite "Test Payload": asyncTest "Send text message with multiple frames": const FrameSize = 3000 - let testData = rndStr(FrameSize * 3) + let testData = rndStr(FrameSize * 3 + 100) proc handle(request: HttpRequest) {.async.} = check request.uri.path == WSPath - let server = WSServer.new(protos = ["proto"]) + let server = WSServer.new(protos = ["proto"], frameSize = FrameSize) let ws = await server.handleRequest(request) let res = await ws.recvMsg() diff --git a/websock/session.nim b/websock/session.nim index 70800df3..5c0dbbb5 100644 --- a/websock/session.nim +++ b/websock/session.nim @@ -37,21 +37,21 @@ proc writeMessage*(ws: WSSession, let maxSize = ws.frameSize var i = 0 while ws.readyState notin {ReadyState.Closing}: - let len = min(data.len, maxSize) + let canSend = min(data.len - i, maxSize) let frame = Frame( - fin: if (len + i >= data.len): true else: false, + fin: if (canSend + i >= data.len): true else: false, rsv1: false, rsv2: false, rsv3: false, opcode: if i > 0: Opcode.Cont else: opcode, # fragments have to be `Continuation` frames mask: ws.masked, - data: data[i ..< len + i], + data: data[i ..< canSend + i], maskKey: maskKey) let encoded = await frame.encode(extensions) await ws.stream.writer.write(encoded) - i += len + i += canSend if i >= data.len: break