Skip to content

Commit

Permalink
Add public API to send an unsolicited pong message (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
tkrajacic committed Jul 12, 2023
1 parent 81b427d commit 90b7605
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Sources/HummingbirdWSCore/WebSocket.swift
Expand Up @@ -133,6 +133,17 @@ public final class HBWebSocket {
}
}

/// Send an unsolicited Pong message
///
/// This can be used as a unidirectional heartbeat.
/// See [RFC6455](https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.3)
/// - Parameter promise: promise that is completed when pong message has been sent
public func sendPong(_ buffer: ByteBuffer, promise: EventLoopPromise<Void>?) {
self.channel.eventLoop.execute {
self.send(buffer: buffer, opcode: .pong)
}
}

/// Send ping and setup task to check for pong and send new ping
public func initiateAutoPing(interval: TimeAmount) {
guard self.channel.isActive else {
Expand Down
18 changes: 18 additions & 0 deletions Tests/HummingbirdWebSocketTests/WebSocketTests.swift
Expand Up @@ -346,6 +346,24 @@ final class HummingbirdWebSocketTests: XCTestCase {
try promise.wait()
}

func testUnsolicitedPong() throws {
let promise = TimeoutPromise(eventLoop: Self.eventLoopGroup.next(), timeout: .seconds(10))

let app = try self.setupClientAndServer(
onServer: { ws in
ws.onPong { _ in
promise.succeed()
}
},
onClient: { ws in
ws.sendPong(.init(), promise: nil)
}
)
defer { app.stop() }

try promise.wait()
}

func testQuery() throws {
let app = HBApplication(configuration: .init(address: .hostname(port: 8080)))
// add HTTP to WebSocket upgrade
Expand Down

0 comments on commit 90b7605

Please sign in to comment.