diff --git a/Sources/FoundationNetworking/URLSession/URLSessionTask.swift b/Sources/FoundationNetworking/URLSession/URLSessionTask.swift index 3771945750..95b14f38ad 100644 --- a/Sources/FoundationNetworking/URLSession/URLSessionTask.swift +++ b/Sources/FoundationNetworking/URLSession/URLSessionTask.swift @@ -865,6 +865,12 @@ open class URLSessionWebSocketTask : URLSessionTask { } } self.receiveCompletionHandlers.removeAll() + for handler in self.pongCompletionHandlers { + session.delegateQueue.addOperation { + handler(taskError) + } + } + self.pongCompletionHandlers.removeAll() self._getProtocol { urlProtocol in self.workQueue.async { if self.handshakeCompleted && self.state != .completed { diff --git a/Tests/Foundation/Tests/TestURLSession.swift b/Tests/Foundation/Tests/TestURLSession.swift index 260d93ce3f..d3b9e3c37c 100644 --- a/Tests/Foundation/Tests/TestURLSession.swift +++ b/Tests/Foundation/Tests/TestURLSession.swift @@ -2064,8 +2064,15 @@ class TestURLSession: LoopbackServerTest { XCTFail("Unexpected Data Message") } - try await task.sendPing() - + do { + try await task.sendPing() + // Server hasn't closed the connection yet + } catch { + // Server closed the connection before we could process the pong + let urlError = try XCTUnwrap(error as? URLError) + XCTAssertEqual(urlError._nsError.code, NSURLErrorNetworkConnectionLost) + } + wait(for: [delegate.expectation], timeout: 50) do {