WebSocket client

WebSocket client is defined by the following protocol:

public protocol WebSocketClientProtocol {
    typealias Subscription = (URLSessionWebSocketTask.Message?) -> Void
    typealias ErrorSubscription = (Swift.Error) -> Void
    
    init(
        secure: Bool,
        host: String,
        path: String?,
        params: [String: String?],
        port: Int?,
        policy: WebSocketClientSubscriptionPolicy
    )
    
    func sendMessage(_ message: URLSessionWebSocketTask.Message, completion: @escaping (Swift.Error?) -> Void)
    func subscribe(subscription: @escaping Subscription)
    func subscribeToErrors(_ errorSubscription: @escaping ErrorSubscription)

To create a WebSocket client, a subscription policy should be provided:

public enum WebSocketClientSubscriptionPolicy {
    case none
    case firstSubscriber
    case allSubscribers
}

This policy describes how to handle incoming messages which have been received before the very first subscriptions. It's a well known issue on some of the Substrate nodes, when you subscribe to the event, but its response comes earlier than subscription confirmation.

The subscription policy can be of three types:

  1. .none: No new subscriber recieves pending data

  2. .firstSubscriber: Only the first subscriber recieves pending data

  3. .allSubscribers: All subscribers recieve pending data

To send a message the below method should be used:

func sendMessage(_ message: URLSessionWebSocketTask.Message, completion: @escaping (Swift.Error?) -> Void)

To subscribe to updates, call the following method:

typealias Subscription = (URLSessionWebSocketTask.Message?) -> Void

func subscribe(subscription: @escaping Subscription)

To subscribe to errors, use this method:

typealias ErrorSubscription = (Swift.Error) -> Void

func subscribeToErrors(_ errorSubscription: @escaping ErrorSubscription)

Last updated