From 858cb47b88e989e50a3bb77f8b0bbe4ff902e2bb Mon Sep 17 00:00:00 2001 From: yuuzheng Date: Sun, 2 Jan 2022 15:54:58 +0800 Subject: [PATCH] Fix multi-thread issues on socket client --- Sources/Heze/Socket/HezeSocketHandler.swift | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Sources/Heze/Socket/HezeSocketHandler.swift b/Sources/Heze/Socket/HezeSocketHandler.swift index 64d8e60..d4b19b3 100644 --- a/Sources/Heze/Socket/HezeSocketHandler.swift +++ b/Sources/Heze/Socket/HezeSocketHandler.swift @@ -14,7 +14,7 @@ open class HezeSocketHandler: HezeHandler, WebSocketSessionHandler { public var socket: WebSocket? = nil public var remoteHost: String? public var remotePort: UInt16? - public var queue = DispatchQueue(label: "heze.socket.handler", attributes: .concurrent) + public var queue = DispatchQueue(label: "heze.socket.handler") public var buffer = [UInt8]() open var socketProtocol: String? { @@ -108,10 +108,14 @@ open class HezeSocketHandler: HezeHandler, WebSocketSessionHandler { open func handleBytes(_ bytes: [UInt8], opcodeType: WebSocket.OpcodeType, final: Bool, socket: WebSocket, completion: @escaping (HezeResponsable?) -> Void) { buffer.append(contentsOf: bytes) if final { - defer { - buffer.removeAll(keepingCapacity: false) + receiveBytes(buffer) { [weak self] in + guard let self = self else { + completion($0) + return + } + self.buffer.removeAll(keepingCapacity: false) + completion($0) } - receiveBytes(buffer, completion: completion) } else { completion(nil) }