Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions Sources/NWWebSocket/Model/Client/NWWebSocket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ open class NWWebSocket: WebSocketConnection {
guard !isListening else { return }
isListening = true

connection?.receiveMessage { [weak self] (data, context, _, error) in
connection?.receiveMessage { [weak self] (data, context, isComplete, error) in
guard let self = self else {
return
}
Expand All @@ -198,7 +198,11 @@ open class NWWebSocket: WebSocketConnection {
return
}

if let data = data, !data.isEmpty, let context = context {
if Self.shouldDeliverReceivedMessage(
data: data,
context: context,
isComplete: isComplete
), let data = data, let context = context {
self.receiveMessage(data: data, context: context)
}

Expand All @@ -212,6 +216,15 @@ open class NWWebSocket: WebSocketConnection {
}
}

/// Return `true` only for a complete message that contains data and metadata.
internal static func shouldDeliverReceivedMessage(
data: Data?,
context: NWConnection.ContentContext?,
isComplete: Bool
) -> Bool {
isComplete && data?.isEmpty == false && context != nil
}

/// Ping the WebSocket periodically.
/// - Parameter interval: The `TimeInterval` (in seconds) with which to ping the server.
open func ping(interval: TimeInterval) {
Expand Down
54 changes: 54 additions & 0 deletions Tests/NWWebSocketTests/ReceiveCompletionTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Foundation
import Network
@testable import NWWebSocket
import XCTest

final class ReceiveCompletionTests: XCTestCase {
func testCompleteMessageIsDelivered() {
XCTAssertTrue(
NWWebSocket.shouldDeliverReceivedMessage(
data: Data("{}".utf8),
context: textContext,
isComplete: true
)
)
}

func testIncompleteMessageIsNotDelivered() {
XCTAssertFalse(
NWWebSocket.shouldDeliverReceivedMessage(
data: Data("{\"partial\":".utf8),
context: textContext,
isComplete: false
)
)
}

func testEmptyMessageIsNotDelivered() {
XCTAssertFalse(
NWWebSocket.shouldDeliverReceivedMessage(
data: Data(),
context: textContext,
isComplete: true
)
)
}

func testMessageWithoutContextIsNotDelivered() {
XCTAssertFalse(
NWWebSocket.shouldDeliverReceivedMessage(
data: Data("{}".utf8),
context: nil,
isComplete: true
)
)
}

private var textContext: NWConnection.ContentContext {
let metadata = NWProtocolWebSocket.Metadata(opcode: .text)
return NWConnection.ContentContext(
identifier: "test-text-message",
metadata: [metadata]
)
}
}