### Install Gem Dependencies Source: https://github.com/daltoniam/starscream/blob/master/examples/SimpleTest/README.md Installs the necessary Ruby gem dependencies for the websocket server. ```bash gem install em-websocket gem install faker ``` -------------------------------- ### Run WebSocket Server Source: https://github.com/daltoniam/starscream/blob/master/examples/SimpleTest/README.md Starts the Ruby-based websocket server. ```bash ruby ws-server.rb ``` -------------------------------- ### Standard Production Setup Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/security.md Example of a standard production setup for WebSocket connection with default security. ```swift let request = URLRequest(url: URL(string: "wss://api.example.com")!) let socket = WebSocket(request: request) // FoundationSecurity() is used by default, validates against system trust store ``` -------------------------------- ### WSEngine Initialization Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/engine.md Example of initializing WSEngine with custom components. ```swift let transport = TCPTransport() let pinner = FoundationSecurity(allowSelfSigned: true) let compression = WSCompression() let engine = WSEngine(transport: transport, certPinner: pinner, compressionHandler: compression) ``` -------------------------------- ### Server Error Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of how to catch and handle server startup errors. ```swift if let error = server.start(address: "0.0.0.0", port: 8080) { if let wsError = error as? WSError, wsError.type == .serverError { print("Server startup failed: \(wsError.message)") } } ``` -------------------------------- ### WSError Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/types.md Example of creating a WSError. ```swift let error = WSError(type: .protocolError, message: "Invalid frame", code: CloseCode.protocolError.rawValue) ``` -------------------------------- ### WSFramer Initialization Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/framing.md Example of initializing WSFramer for client and server. ```swift // Client framing let clientFramer = WSFramer() // Server framing let serverFramer = WSFramer(isServer: true) ``` -------------------------------- ### NativeEngine Initialization Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/engine.md Example of initializing NativeEngine and creating a WebSocket instance. ```swift let engine = NativeEngine() let socket = WebSocket(request: request, engine: engine) ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md A comprehensive example demonstrating how to configure a WebSocket client with custom URL requests, security, and compression. ```swift import Starscream class APIClient { var socket: WebSocket? func connect() { // Configure URLRequest var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.timeoutInterval = 10 request.setValue("Bearer token123", forHTTPHeaderField: "Authorization") request.setValue("chat", forHTTPHeaderField: "Sec-WebSocket-Protocol") // Configure security let pinner = FoundationSecurity(allowSelfSigned: false) // Configure compression let compression = WSCompression() // Create WebSocket socket = WebSocket(request: request, certPinner: pinner, compressionHandler: compression) // Configure callbacks socket?.callbackQueue = DispatchQueue.main socket?.respondToPingWithPong = true // Set delegate socket?.delegate = self // Connect socket?.connect() } } extension APIClient: WebSocketDelegate { func didReceive(event: WebSocketEvent, client: WebSocketClient) { switch event { case .connected: print("Connected") socket?.write(string: "Hello") case .text(let message): print("Received: \(message)") case .error(let error): print("Error: \(error)") default: break } } } ``` -------------------------------- ### Engine Selection Logic Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/engine.md Examples demonstrating how to force NativeEngine or explicitly use WSEngine. ```swift // Force NativeEngine on supported platforms let socket = WebSocket(request: request, useCustomEngine: false) // Explicit WSEngine let transport = TCPTransport() let engine = WSEngine(transport: transport) let socket = WebSocket(request: request, engine: engine) ``` -------------------------------- ### CocoaPods Installation Source: https://github.com/daltoniam/starscream/blob/master/README.md Example Podfile configuration for using Starscream with CocoaPods. ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '12.0' use_frameworks! pod 'Starscream', '~> 4.0.6' ``` -------------------------------- ### Carthage Installation Source: https://github.com/daltoniam/starscream/blob/master/README.md Example Cartfile configuration for using Starscream with Carthage. ```plaintext github "daltoniam/Starscream" >= 4.0.6 ``` -------------------------------- ### Server Startup Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Starting a WebSocket server on a specified address and port. ```swift let server = WebSocketServer() // Basic startup if let error = server.start(address: "0.0.0.0", port: 8080) { print("Server startup failed: \(error)") } // Localhost only (testing) server.start(address: "127.0.0.1", port: 8080) // Specific interface server.start(address: "192.168.1.100", port: 8080) ``` -------------------------------- ### Complete Server Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/server.md A full example demonstrating how to set up and run a basic WebSocket server using Starscream, including event handling for connected clients, text messages, and disconnections. ```swift import Starscream let server = WebSocketServer() server.onEvent = { event in switch event { case .connected(let connection, let headers): print("Client connected") // Send welcome message connection.write(data: "Welcome!".data(using: .utf8)!, opcode: .textFrame) case .text(let connection, let message): print("Received: \(message)") // Echo back to sender connection.write(data: message.data(using: .utf8)!, opcode: .textFrame) case .binary(let connection, let data): print("Received binary: \(data.count) bytes") case .disconnected(let connection, let reason, let code): print("Client disconnected: \(reason) (\(code))") case .ping(let connection, let data): print("Ping received") // Auto-responds with pong case .pong: print("Pong received") @unknown default: break } } if let error = server.start(address: "0.0.0.0", port: 8080) { print("Failed to start server: \(error)") } else { print("Server listening on port 8080") } ``` -------------------------------- ### Port Already in Use (Server) Error Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of an error when the WebSocket server cannot start because the specified port is already in use. ```swift WSError(type: .serverError, message: "unable to start the listener at 0.0.0.0:8080", code: 0) ``` ```swift // Try different port if let error = server.start(address: "0.0.0.0", port: 8080) { print("Port 8080 in use, trying 8081") server.start(address: "0.0.0.0", port: 8081) } // Or stop the process using the port ``` -------------------------------- ### Compression Error Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of how to catch and handle a compression error. ```swift case .error(let error): if let wsError = error as? WSError, wsError.type == .compressionError { print("Compression failed: \(wsError.message)") } ``` -------------------------------- ### load(headers:) Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/compression.md Example of parsing compression parameters from HTTP response headers. ```swift compression.load(headers: responseHeaders) // Now compression is configured with server's parameters ``` -------------------------------- ### createWriteFrame Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/framing.md Example of creating a text frame and sending it. ```swift let payload = "Hello".data(using: .utf8)! let frame = framer.createWriteFrame(opcode: .textFrame, payload: payload, isCompressed: false) transport.write(data: frame) ``` -------------------------------- ### Custom Stream Configuration (FoundationTransport) Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/security.md Example of configuring custom TLS setup for FoundationTransport. ```swift let transport = FoundationTransport { input, output in if /* custom TLS setup needed */ { let key = kCFStreamPropertySocketSecurityLevel CFReadStreamSetProperty(input, key as CFStreamPropertyKey, kCFStreamSocketSecurityLevelNegotiatedSSL) CFWriteStreamSetProperty(output, key as CFStreamPropertyKey, kCFStreamSocketSecurityLevelNegotiatedSSL) } } ``` -------------------------------- ### Write String Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Examples of sending a string message with and without a completion handler. ```swift socket.write(string: "Hello Server!") { print("Message sent") } // Or without completion: socket.write(string: "Hello Server!") ``` -------------------------------- ### Server Implementation Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/README.md Example of setting up a basic WebSocket server. ```swift let server = WebSocketServer() server.onEvent = { event in switch event { case .connected(let connection, let headers): print("Client connected") connection.write(data: "Welcome!".data(using: .utf8)!, opcode: .textFrame) case .text(let connection, let message): print("Received: \(message)") connection.write(data: message.data(using: .utf8)!, opcode: .textFrame) case .disconnected(let connection, let reason, let code): print("Client disconnected: \(reason)") default: break } } server.start(address: "0.0.0.0", port: 8080) ``` -------------------------------- ### WebSocketServer start(address:port:) Method Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/server.md Start the server listening for connections on the specified address and port. ```swift public func start(address: String, port: UInt16) -> Error? ``` ```swift if let error = server.start(address: "0.0.0.0", port: 8080) { print("Failed to start: \(error)") } else { print("Server started on port 8080") } ``` -------------------------------- ### Protocol Error Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of how to catch and handle protocol errors. ```swift case .error(let error): if let wsError = error as? WSError, wsError.type == .protocolError { print("Protocol error: \(wsError.message) (code: \(wsError.code))") } ``` -------------------------------- ### Swift Package Manager Installation Source: https://github.com/daltoniam/starscream/blob/master/README.md Example of adding Starscream as a dependency in Package.swift for Swift Package Manager. ```swift dependencies: [ .package(url: "https://github.com/daltoniam/Starscream.git", from: "4.0.6") ] ``` -------------------------------- ### Write Pong Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Example of sending a pong frame in response to a ping event. ```swift socket.onEvent = { event in if case .ping(let data) = event { socket.write(pong: data ?? Data()) } } ``` -------------------------------- ### Automatic Reconnection Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example demonstrating automatic reconnection strategy for WebSocket connections. ```swift class RobustWebSocket { var socket: WebSocket? var shouldReconnect = true func connect(url: URL) { let request = URLRequest(url: url) socket = WebSocket(request: request) socket?.delegate = self socket?.connect() } func handleDisconnection() { if shouldReconnect { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.connect(url: ...) } } } } extension RobustWebSocket: WebSocketDelegate { func didReceive(event: WebSocketEvent, client: WebSocketClient) { switch event { case .disconnected: handleDisconnection() case .error(let error): print("Error: \(error)") handleDisconnection() default: break } } } ``` -------------------------------- ### Write Pong (no completion) Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Example of sending a pong frame using the extension method. ```swift socket.write(pong: Data()) ``` -------------------------------- ### Force Disconnect Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Example of forcing a disconnect. ```swift socket.forceDisconnect() ``` -------------------------------- ### Manual Installation (Xcode Project) Source: https://github.com/daltoniam/starscream/blob/master/README.md Instructions for manually adding Starscream.framework to an Xcode project. ```bash # Add the Starscream.xcodeproj to your Xcode project. # In "Build Phases", add the Starscream.framework to "Link Binary with Libraries". # Add a "New Copy Files Phase", rename to "Copy Frameworks", set Destination to "Frameworks", and add Starscream.framework. ``` -------------------------------- ### add(frame:) Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/framing.md Example of processing a frame using FrameCollector. ```swift frameHandler.add(frame: frame) // Delegate receives complete messages via didForm() ``` -------------------------------- ### Write Data (Binary) Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Examples of sending binary data with and without a completion handler. ```swift let binaryData = "Binary payload".data(using: .utf8)! socket.write(data: binaryData) socket.write(data: binaryData) { print("Binary data sent") } ``` -------------------------------- ### Security Error Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of how to catch and handle security errors, checking specific error codes. ```swift case .error(let error): if let wsError = error as? WSError, wsError.type == .securityError { if wsError.code == SecurityErrorCode.acceptFailed.rawValue { print("Server accept header invalid") } else if wsError.code == SecurityErrorCode.pinningFailed.rawValue { print("Certificate validation failed") } } ``` -------------------------------- ### Enable Compression Source: https://github.com/daltoniam/starscream/blob/master/README.md Example of how to enable compression by providing a compressionHandler. ```swift var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) let compression = WSCompression() let socket = WebSocket(request: request, compressionHandler: compression) ``` -------------------------------- ### Delegate-Based Error Handling Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example demonstrating how to handle WebSocket errors using a delegate pattern. ```swift extension ViewController: WebSocketDelegate { func didReceive(event: WebSocketEvent, client: WebSocketClient) { switch event { case .connected: print("Connected") case .disconnected: print("Disconnected") case .error(let error): handleWebSocketError(error) default: break } } func handleWebSocketError(_ error: Error?) { guard let error = error else { return } if let wsError = error as? WSError { switch wsError.type { case .securityError: print("Security error: \(wsError.message)") case .compressionError: print("Compression error: \(wsError.message)") case .protocolError: print("Protocol error: \(wsError.message) (code: \(wsError.code))") case .serverError: print("Server error: \(wsError.message)") } } else if let httpError = error as? HTTPUpgradeError { print("HTTP upgrade failed: \(httpError)") } else { print("Unknown error: \(error)") } } } ``` -------------------------------- ### Write Data (Binary, no completion) Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Example of sending binary data using the extension method. ```swift let data = Data([0xFF, 0xEE, 0xDD]) socket.write(data: data) ``` -------------------------------- ### WSCompression Initialization Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/compression.md Initialize WSCompression with default DEFLATE parameters and use it with a WebSocket instance. ```swift let compression = WSCompression() let socket = WebSocket(request: request, compressionHandler: compression) ``` -------------------------------- ### Write Ping Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Examples of sending a ping frame with or without a payload and completion handler. ```swift socket.write(ping: Data()) socket.write(ping: Data("heartbeat".utf8)) { print("Ping sent") } ``` -------------------------------- ### Write Ping (no completion) Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Example of sending a ping frame using the extension method. ```swift socket.write(ping: Data()) ``` -------------------------------- ### HTTPUpgradeError Example Usage Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of how to handle HTTPUpgradeError in a switch statement. ```swift case .error(let error): if let httpError = error as? HTTPUpgradeError { switch httpError { case .notAnUpgrade(let status, let headers): print("HTTP upgrade rejected with status \(status)") print("Headers: \(headers)") case .invalidData: print("Invalid HTTP response received") } } ``` -------------------------------- ### FoundationTransportError Example Usage Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of how to handle FoundationTransportError in a switch statement. ```swift case .error(let error): if let ftError = error as? FoundationTransportError { switch ftError { case .invalidRequest: print("Invalid URL format") case .invalidOutputStream: print("Cannot create output stream") case .timeout: print("Connection timeout") } } ``` -------------------------------- ### Disconnect Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Examples of disconnecting with default or specified close codes. ```swift socket.disconnect() // Use default close code 1000 (normal closure) socket.disconnect(closeCode: CloseCode.goingAway.rawValue) ``` -------------------------------- ### Broadcasting to All Clients Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/server.md An example of an EchoServer that broadcasts incoming text messages to all connected clients. ```swift class EchoServer { private var connections: [String: Connection] = [:] let server = WebSocketServer() init() { server.onEvent = { [weak self] event in self?.handleEvent(event) } } func start() { server.start(address: "0.0.0.0", port: 8080) } private func handleEvent(_ event: ServerEvent) { switch event { case .connected(let conn, _): let connection = conn as! ServerConnection connections[connection.uuid] = conn case .text(let conn, let message): let connection = conn as! ServerConnection // Broadcast to all clients for (_, client) in connections { client.write(data: message.data(using: .utf8)!, opcode: .textFrame) } case .disconnected(let conn, _, _): let connection = conn as! ServerConnection connections.removeValue(forKey: connection.uuid) default: break } } } ``` -------------------------------- ### Install Xcode command line tools Source: https://github.com/daltoniam/starscream/blob/master/fastlane/README.md Ensures the latest version of the Xcode command line tools are installed. ```shell xcode-select --install ``` -------------------------------- ### Write String Data Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Example of sending text data as a Data object. ```swift let textData = "Hello Server".data(using: .utf8)! socket.write(stringData: textData) ``` -------------------------------- ### Closure-Based Error Handling Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example demonstrating how to handle WebSocket errors using a closure. ```swift socket.onEvent = { event in if case .error(let error) = event { if let wsError = error as? WSError { // Handle specific WSError } else if let httpError = error as? HTTPUpgradeError { // Handle HTTP errors } else { // Handle other errors } } } ``` -------------------------------- ### Custom Headers Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Example of setting custom HTTP headers for a WebSocket request. ```swift var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.setValue("Bearer token123", forHTTPHeaderField: "Authorization") request.setValue("custom-header-value", forHTTPHeaderField: "X-Custom-Header") let socket = WebSocket(request: request) ``` -------------------------------- ### Transport Selection Logic Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/transport.md Demonstrates conditional transport selection based on OS version and compiler. ```swift #if os(macOS) && compiler(>=5.3) let transport = TCPTransport() #else let transport = FoundationTransport() #endif ``` -------------------------------- ### Custom Protocol Negotiation Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Example of setting the Sec-WebSocket-Protocol header for custom protocol negotiation. ```swift var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.setValue("chat,superchat", forHTTPHeaderField: "Sec-WebSocket-Protocol") let socket = WebSocket(request: request) ``` -------------------------------- ### NativeEngine Methods Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/engine.md Methods for registering a delegate, starting, stopping, and writing data. ```swift func register(delegate: EngineDelegate) func start(request: URLRequest) func stop(closeCode: UInt16) func forceStop() func write(string: String, completion: (() -> ())?) func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) ``` -------------------------------- ### Enable Compression Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/compression.md Example of enabling compression when creating a WebSocket instance. ```swift let request = URLRequest(url: URL(string: "wss://api.example.com")!) let compression = WSCompression() let socket = WebSocket(request: request, compressionHandler: compression) socket.onEvent = { event in case .connected: print("Connected with compression support") socket.write(string: "Hello") // Automatically compressed case .text(let msg): print("Received: \(msg)") // Automatically decompressed default: break } socket.connect() ``` -------------------------------- ### Allow Self-Signed Certificates (Development) Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/security.md Example of how to allow self-signed certificates for development purposes. ```swift let request = URLRequest(url: URL(string: "wss://localhost:8443")!) let pinner = FoundationSecurity(allowSelfSigned: true) let socket = WebSocket(request: request, certPinner: pinner) ``` -------------------------------- ### With Compression and Security Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/README.md Example of connecting to a WebSocket with custom headers, security, and compression. ```swift var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.timeoutInterval = 10 request.setValue("Bearer token", forHTTPHeaderField: "Authorization") let pinner = FoundationSecurity(allowSelfSigned: false) let compression = WSCompression() let socket = WebSocket(request: request, certPinner: pinner, compressionHandler: compression) socket.connect() ``` -------------------------------- ### Handle Compression Errors Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/compression.md Example of handling potential compression failures. ```swift if let compressed = handler.compress(data) { // Use compressed data } else { // Compression failed, will use uncompressed } ``` -------------------------------- ### Setting Sec-WebSocket-Protocol Header Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of setting the Sec-WebSocket-Protocol header to specify a subprotocol. ```swift var request = URLRequest(url: url) request.setValue("chat", forHTTPHeaderField: "Sec-WebSocket-Protocol") ``` -------------------------------- ### URL Parsing Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/transport.md Parses a URL into its host, port, and TLS flag components using the getParts() extension. ```swift if let parts = url.getParts() { print("Host: \(parts.host), Port: \(parts.port), TLS: \(parts.isTLS)") } ``` -------------------------------- ### Custom Callback Queue Source: https://github.com/daltoniam/starscream/blob/master/README.md Example of setting a custom callback queue for delegate methods. ```swift socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) //create a custom queue socket.callbackQueue = DispatchQueue(label: "com.vluxe.starscream.myapp") ``` -------------------------------- ### Malformed WebSocket Frame Error Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of an error indicating a malformed WebSocket frame received from the server. ```swift WSError(type: .protocolError, message: "...", code: 1002) ``` -------------------------------- ### Check Compression Availability Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/compression.md Example of checking if compression is active. ```swift if let compression = compressionHandler, compression.compressor != nil && compression.decompressor != nil { print("Compression is active") } ``` -------------------------------- ### Invalid Compressed Data Error Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of an error related to invalid compressed data during WebSocket communication. ```swift WSError(type: .compressionError, message: "Error on decompressing", code: 0) ``` ```swift let socket = WebSocket(request: request) // No compressionHandler ``` -------------------------------- ### FoundationTransport Connection Example Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/transport.md Connects to a WebSocket server using FoundationTransport with a specified timeout and optional certificate pinning. ```swift let transport = FoundationTransport() transport.register(delegate: self) transport.connect(url: url, timeout: 5) ``` -------------------------------- ### Increasing Connection Timeout Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Example of setting a custom timeout interval for a URLRequest. ```swift var request = URLRequest(url: url) request.timeoutInterval = 30 // 30 seconds let socket = WebSocket(request: request) ``` -------------------------------- ### Valid and Invalid WebSocket URLs Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/errors.md Examples of valid and invalid URL formats for WebSocket connections. ```swift // Valid URLs: URL(string: "ws://example.com") URL(string: "wss://example.com:8080") URL(string: "ws://192.168.1.1/chat") // Invalid: URL(string: "http://example.com") // Wrong scheme URL(string: "example.com") // Missing scheme ``` -------------------------------- ### WSEngine Initialization Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/engine.md Initialize WSEngine with custom components. ```swift public init(transport: Transport, certPinner: CertificatePinning? = nil, headerValidator: HeaderValidator = FoundationSecurity(), httpHandler: HTTPHandler = FoundationHTTPHandler(), framer: Framer = WSFramer(), compressionHandler: CompressionHandler? = nil) ``` -------------------------------- ### WSEngine Options Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Customizing the WSEngine with various handlers for transport, security, and framing. ```swift let transport = TCPTransport() let pinner = FoundationSecurity() let compression = WSCompression() let engine = WSEngine( transport: transport, certPinner: pinner, headerValidator: FoundationSecurity(), // Validates Sec-WebSocket-Accept httpHandler: FoundationHTTPHandler(), // Handles HTTP upgrade framer: WSFramer(), // Encodes/decodes frames compressionHandler: compression ) let socket = WebSocket(request: request, engine: engine) ``` -------------------------------- ### WebSocket Upgrade Handshake - Client Request Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Example of a client's HTTP request for a WebSocket upgrade. ```http GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13 ``` -------------------------------- ### WebSocket Upgrade Handshake - Server Response Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Example of a server's HTTP response to a WebSocket upgrade request. ```http HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= ``` -------------------------------- ### init(request:certPinner:compressionHandler:useCustomEngine:) Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Convenience initializer that automatically selects the appropriate Engine based on iOS/macOS version. Uses NativeEngine on macOS 10.15+ / iOS 13.0+ if `useCustomEngine` is false, otherwise uses WSEngine. ```swift public convenience init(request: URLRequest, certPinner: CertificatePinning? = FoundationSecurity(), compressionHandler: CompressionHandler? = nil, useCustomEngine: Bool = true) ``` ```swift var request = URLRequest(url: URL(string: "wss://localhost:8080")!) request.timeoutInterval = 5 let pinner = FoundationSecurity(allowSelfSigned: true) let compression = WSCompression() let socket = WebSocket(request: request, certPinner: pinner, compressionHandler: compression) socket.delegate = self socket.connect() ``` -------------------------------- ### init(allowSelfSigned:) Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/security.md Initialize with standard or permissive SSL validation. ```swift public init(allowSelfSigned: Bool = false) ``` ```swift let pinner = FoundationSecurity() let devPinner = FoundationSecurity(allowSelfSigned: true) let socket = WebSocket(request: request, certPinner: devPinner) ``` -------------------------------- ### Engine Selection Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Shows different ways to select the WebSocket engine, including automatic, forcing native, and explicit WSEngine. ```swift // Automatic engine selection (recommended) let socket = WebSocket(request: request) // Force NativeEngine on supported platforms (iOS 13+, macOS 10.15+) let socket = WebSocket(request: request, useCustomEngine: false) // Explicit WSEngine with custom transport let transport = TCPTransport() let engine = WSEngine(transport: transport) let socket = WebSocket(request: request, engine: engine) ``` -------------------------------- ### Basic Connection Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Establishes a basic WebSocket connection with a given URL. ```swift let url = URL(string: "wss://api.example.com")! let request = URLRequest(url: url) let socket = WebSocket(request: request) ``` -------------------------------- ### Callback Queue Configuration Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Shows how to configure the dispatch queue for delegate methods and event closures. ```swift let socket = WebSocket(request: request) // All delegate methods and onEvent closures called on main thread (default) socket.callbackQueue = DispatchQueue.main // Custom queue for delegate callbacks let customQueue = DispatchQueue(label: "com.example.websocket.callbacks") socket.callbackQueue = customQueue // Background queue socket.callbackQueue = DispatchQueue.global(qos: .background) ``` -------------------------------- ### Cookie Handling Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Demonstrates how cookies are automatically included and how to add them manually. ```swift // Cookies for the domain are automatically added let socket = WebSocket(request: request) // To add cookies manually: var request = URLRequest(url: url) let headers = HTTPCookie.requestHeaderFields(with: cookies) for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } ``` -------------------------------- ### WebSocketServer Initialization Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/server.md Initialize an empty WebSocket server. ```swift public init() ``` ```swift let server = WebSocketServer() let error = server.start(address: "0.0.0.0", port: 8080) if error != nil { print("Failed to start server: \(error!)") } ``` -------------------------------- ### Ping/Pong Handling Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Demonstrates how to configure automatic or manual ping/pong responses. Note that NativeEngine always auto-responds. ```swift let socket = WebSocket(request: request) // Automatically respond to pings with pongs (default for WSEngine) socket.respondToPingWithPong = true // Manual ping response handling (WSEngine only) socket.respondToPingWithPong = false socket.onEvent = { event in if case .ping(let data) = event { socket.write(pong: data ?? Data()) } } ``` -------------------------------- ### init(request:engine:) Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Initialize WebSocket with a URLRequest and custom Engine implementation. ```swift public init(request: URLRequest, engine: Engine) ``` ```swift let request = URLRequest(url: URL(string: "ws://localhost:8080")!) let engine = WSEngine(transport: TCPTransport()) let socket = WebSocket(request: request, engine: engine) ``` -------------------------------- ### Production Configuration Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Recommended configuration for production environments, emphasizing a reasonable timeout and default security/compression settings. ```swift var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.timeoutInterval = 30 // 30 second timeout let socket = WebSocket(request: request) socket.callbackQueue = DispatchQueue.main // Security: Default FoundationSecurity() validates against trust store // Compression: Enabled automatically if server supports ``` -------------------------------- ### WSEngine Properties Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/engine.md Controls automatic ping/pong response handling. Default is `true`. ```swift public var respondToPingWithPong: Bool ``` -------------------------------- ### Compression Extension Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Enabling and negotiating WebSocket compression using the WSCompression handler. ```swift // Client requests compression support let compression = WSCompression() let socket = WebSocket(request: request, compressionHandler: compression) // Sends: Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits; server_max_window_bits=15 // Server responds with compression parameters // Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15 ``` -------------------------------- ### Handle Decompression Errors Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/compression.md Example of handling potential decompression failures. ```swift if let decompressed = handler.decompress(data, isFinal: true) { // Successfully decompressed } else { // Decompression failed } ``` -------------------------------- ### NativeEngine Initialization Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/engine.md Initialize NativeEngine with default URLSession configuration. ```swift public init() ``` -------------------------------- ### Subprotocol Negotiation Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Configuring subprotocol negotiation by setting the Sec-WebSocket-Protocol header. ```swift var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.setValue("chat,superchat", forHTTPHeaderField: "Sec-WebSocket-Protocol") let socket = WebSocket(request: request) // Server responds with one selected subprotocol: // Sec-WebSocket-Protocol: chat ``` -------------------------------- ### Disable Compression After Connection Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/compression.md Example of disabling compression by not passing a compression handler. ```swift // Don't pass compressionHandler let socket = WebSocket(request: request) // No compression ``` -------------------------------- ### WSEngine Class Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/engine.md Custom WebSocket implementation handling the complete RFC 6455 protocol. Supports compression, custom transports, and certificate pinning. ```swift public class WSEngine: Engine, TransportEventClient, FramerEventClient, FrameCollectorDelegate, HTTPHandlerDelegate ``` -------------------------------- ### Development Configuration Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Configuration suitable for development, allowing self-signed certificates and a longer timeout for easier debugging. ```swift var request = URLRequest(url: URL(string: "wss://localhost:8080")!) request.timeoutInterval = 60 // Longer for debugging let pinner = FoundationSecurity(allowSelfSigned: true) let socket = WebSocket(request: request, certPinner: pinner) ``` -------------------------------- ### WSFramer Initialization Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/framing.md Initialize the framer. ```swift public init(isServer: Bool = false) ``` -------------------------------- ### connect() Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Initiates the WebSocket connection. The delegate will receive a `.connected` event on success or `.error` event on failure. ```swift public func connect() ``` ```swift socket.connect() ``` -------------------------------- ### WSCompression load(headers:) Method Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/compression.md Parse Sec-WebSocket-Extensions header and configure compressor/decompressor. Supported parameters include server_max_window_bits, client_max_window_bits, server_no_context_takeover, and client_no_context_takeover. ```swift public func load(headers: [String: String]) // Server response header: // Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15 compression.load(headers: ["Sec-WebSocket-Extensions": "permessage-deflate; server_max_window_bits=15"]) ``` -------------------------------- ### URL getParts() Extension Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Extracts host, port, and TLS flag from a URL. ```swift public func getParts() -> URLParts? ``` -------------------------------- ### FoundationTransport Initialization with Stream Configuration Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/transport.md Initializes FoundationTransport with an optional closure to configure input and output streams after they are created. ```swift let transport = FoundationTransport { input, output in // Custom stream setup input.setProperty(kSecAttr as String, forKey: kCFStreamPropertySecurityLevel as NSString) } ``` -------------------------------- ### Certificate Pinning Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Illustrates certificate pinning options, including default validation, allowing self-signed certificates, and custom pinning logic. ```swift // Default: Validate against system trust store let socket = WebSocket(request: request) // Allow self-signed certificates (development only) let pinner = FoundationSecurity(allowSelfSigned: true) let socket = WebSocket(request: request, certPinner: pinner) // Custom certificate pinning class MyPinner: CertificatePinning { func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) { // Custom validation logic } } let socket = WebSocket(request: request, certPinner: MyPinner()) ``` -------------------------------- ### Low-Latency Configuration Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Configuration focused on minimizing latency by disabling compression, using the main thread for callbacks for fast UI updates, and enabling automatic ping-pong responses. ```swift var request = URLRequest(url: URL(string: "wss://api.example.com")!) // No compression - reduce latency let socket = WebSocket(request: request) // No compressionHandler socket.callbackQueue = DispatchQueue.main // Fast UI updates socket.respondToPingWithPong = true // Auto-respond quickly ``` -------------------------------- ### Run tests with fastlane Source: https://github.com/daltoniam/starscream/blob/master/fastlane/README.md Command to run tests using fastlane. ```shell [bundle exec] fastlane test ``` -------------------------------- ### High-Performance Configuration Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Configuration optimized for high performance using the Network.framework transport and enabling compression, with a fast timeout and background callback queue. ```swift let transport = TCPTransport() // Network.framework let compression = WSCompression() // Reduce bandwidth let engine = WSEngine(transport: transport, compressionHandler: compression) var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.timeoutInterval = 5 // Faster timeout let socket = WebSocket(request: request, engine: engine) socket.callbackQueue = DispatchQueue.global(qos: .userInitiated) ``` -------------------------------- ### Delegate-Based Handling Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/README.md Shows how to implement WebSocket event handling using a delegate pattern, conforming to the WebSocketDelegate protocol. ```swift class MyViewController: UIViewController, WebSocketDelegate { var socket: WebSocket? func setupWebSocket() { let request = URLRequest(url: URL(string: "wss://api.example.com")!) socket = WebSocket(request: request) socket?.delegate = self socket?.connect() } func didReceive(event: WebSocketEvent, client: WebSocketClient) { switch event { case .connected(let headers): print("Connected: \(headers)") case .text(let message): print("Received: \(message)") case .error(let error): print("Error: \(error)") default: break } } } ``` -------------------------------- ### Import the framework Source: https://github.com/daltoniam/starscream/blob/master/README.md Import the Starscream framework into your Swift project. ```swift import Starscream ``` -------------------------------- ### NativeEngine Class Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/engine.md Uses Apple's native URLSessionWebSocketTask (available on macOS 10.15+, iOS 13.0+, etc.). Provides a lighter-weight alternative to WSEngine but with fewer customization options. ```swift @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public class NativeEngine: NSObject, Engine, URLSessionDataDelegate, URLSessionWebSocketDelegate ``` -------------------------------- ### Basic Client Connection Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/README.md Demonstrates how to establish a basic WebSocket client connection using Starscream, handle connection events, and send/receive text messages. ```swift import Starscream var request = URLRequest(url: URL(string: "wss://api.example.com")!) let socket = WebSocket(request: request) socket.onEvent = { event in switch event { case .connected: print("Connected") socket.write(string: "Hello Server!") case .text(let message): print("Received: \(message)") case .error(let error): print("Error: \(error)") case .disconnected: print("Disconnected") default: break } } socket.connect() ``` -------------------------------- ### HTTPServerHandler createResponse Method Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Creates an HTTP 101 Switching Protocols response. ```swift func createResponse(headers: [String: String]) -> Data ``` -------------------------------- ### sha1Base64() Extension Method Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/types.md Calculate SHA-1 hash and encode as base64. ```swift private func sha1Base64() -> String ``` -------------------------------- ### Message Compression Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Demonstrates how to enable or disable message compression using RFC 7692. ```swift // Compression disabled let socket = WebSocket(request: request) // RFC 7692 compression enabled let compression = WSCompression() let socket = WebSocket(request: request, compressionHandler: compression) ``` -------------------------------- ### createUpgrade Method Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Creates a WebSocket upgrade request by adding required headers to a URLRequest. ```swift public static func createUpgrade(request: URLRequest, supportsCompression: Bool, secKeyValue: String) -> URLRequest ``` ```swift var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.setValue("chat", forHTTPHeaderField: "Sec-WebSocket-Protocol") let secKey = HTTPWSHeader.generateWebSocketKey() let upgradeRequest = HTTPWSHeader.createUpgrade(request: request, supportsCompression: true, secKeyValue: secKey) ``` -------------------------------- ### Self-Signed Certificate Rejected Solution Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/security.md Solution for rejecting self-signed certificates by using FoundationSecurity with allowSelfSigned set to true. ```swift let pinner = FoundationSecurity(allowSelfSigned: true) let socket = WebSocket(request: request, certPinner: pinner) ``` -------------------------------- ### Custom Certificate Pinning Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/security.md Implementation of a custom certificate pinning strategy. ```swift class CustomCertificatePinner: CertificatePinning { private let pinnedPublicKeys: [Data] init(pinnedPublicKeys: [Data]) { self.pinnedPublicKeys = pinnedPublicKeys } func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) { // Extract public key from certificate // Compare against pinnedPublicKeys // Call completion with .success or .failed } } let pinner = CustomCertificatePinner(pinnedPublicKeys: [...]) let socket = WebSocket(request: request, certPinner: pinner) ``` -------------------------------- ### Internal Decompressor Initialization Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/compression.md Initialize decompressor with window size. ```swift init?(windowBits: Int) // Parameter Description: // windowBits: Compression window bits (8-15, default 15) ``` -------------------------------- ### respondToPingWithPong Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/websocket.md Controls whether the socket automatically responds to incoming ping frames with pong frames. Defaults to `true`. Only works with WSEngine (not NativeEngine). ```swift public var respondToPingWithPong: Bool { set { /* ... */ } get { /* ... */ } } ``` ```swift socket.respondToPingWithPong = false // Handle pings manually ``` -------------------------------- ### TCPTransport Initialization with NWConnection Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/transport.md Initialize with an existing NWConnection. Used by WebSocketServer. ```swift public init(connection: NWConnection) ``` ```swift let connection = NWConnection(host: ..., port: ..., using: parameters) let transport = TCPTransport(connection: connection) ``` -------------------------------- ### Deploy new iOS version with fastlane Source: https://github.com/daltoniam/starscream/blob/master/fastlane/README.md Command to deploy a new version of an iOS app using fastlane. ```shell [bundle exec] fastlane ios release ``` -------------------------------- ### FoundationTransport Configuration Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Configuring FoundationTransport using legacy Streams API, with options for custom stream configuration. ```swift // Basic configuration let transport = FoundationTransport() // Custom stream configuration let transport = FoundationTransport { input, output in // Configure input/output streams input.setProperty(NSNumber(value: 30), forKey: Stream.PropertyKey.networkServiceType) } ``` -------------------------------- ### Server Event Handling Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Handles various WebSocket events on the server side, including connection, text/binary messages, disconnection, and pings. ```swift let server = WebSocketServer() server.onEvent = { event in switch event { case .connected(let connection, let headers): print("Client connected: \(headers)") connection.write(data: "Welcome".data(using: .utf8)!, opcode: .textFrame) case .text(let connection, let message): print("Received: \(message)") // Echo back connection.write(data: message.data(using: .utf8)!, opcode: .textFrame) case .binary(let connection, let data): print("Binary: \(data.count) bytes") case .disconnected(let connection, let reason, let code): print("Disconnected: \(reason)") case .ping(let connection, let data): print("Ping") // Auto-responded with pong case .pong, .error: break } } server.start(address: "0.0.0.0", port: 8080) ``` -------------------------------- ### File Structure Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/README.md Overview of the project's file structure. ```text output/ ├── README.md (this file) ├── api-reference/ │ ├── websocket.md │ ├── engine.md │ ├── transport.md │ ├── framing.md │ ├── security.md │ ├── compression.md │ ├── http-handler.md │ └── server.md ├── types.md ├── errors.md └── configuration.md ``` -------------------------------- ### TCPTransport Configuration Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Configuring TCPTransport using Network.framework for enhanced network features. ```swift let transport = TCPTransport() transport.connect(url: url, timeout: 10, certificatePinning: pinner) ``` -------------------------------- ### Connection write(data:opcode:) Method Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/server.md Send a frame to the client. ```swift // Send text connection.write(data: "Hello Client".data(using: .utf8)!, opcode: .textFrame) // Send binary connection.write(data: binaryData, opcode: .binaryFrame) // Send ping connection.write(data: Data(), opcode: .ping) ``` -------------------------------- ### Request Body Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Sets a custom HTTP method and body for the URLRequest. ```swift var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.httpMethod = "GET" // Most WebSockets use GET request.httpBody = "custom=data".data(using: .utf8) let socket = WebSocket(request: request) ``` -------------------------------- ### Timeout Configuration Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/configuration.md Sets a custom connection timeout for the URLRequest. ```swift var request = URLRequest(url: URL(string: "wss://api.example.com")!) request.timeoutInterval = 10 // 10 second connection timeout let socket = WebSocket(request: request) ``` -------------------------------- ### Log Connection Activity Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/server.md This code snippet demonstrates how to log various connection events using the `onEvent` handler. ```swift server.onEvent = { event in switch event { case .connected(let conn, let headers): print("CONNECT: \(headers)") case .text(let conn, let msg): print("TEXT: \(msg)") case .binary(let conn, let data): print("BINARY: \(data.count) bytes") case .disconnected(let conn, let reason, let code): print("DISCONNECT: \(reason) (\(code))") case .ping(let conn, _): print("PING") case .pong(let conn, _): print("PONG") } } ``` -------------------------------- ### WebSocket Upgrade Handshake - Sec-WebSocket-Accept Calculation Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Formula for calculating the Sec-WebSocket-Accept header value. ```plaintext base64(SHA1("dGhlIHNhbXBsZSBub25jZQ==" + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) ``` -------------------------------- ### Connect to the WebSocket Server Source: https://github.com/daltoniam/starscream/blob/master/README.md Establish a connection to a WebSocket server with a specified URL and timeout. The socket instance should be stored as a property to prevent deallocation. ```swift var request = URLRequest(url: URL(string: "http://localhost:8080")!) request.timeoutInterval = 5 socket = WebSocket(request: request) socket.delegate = self socket.connect() ``` -------------------------------- ### URL isTLSScheme Extension Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Checks if the URL scheme is 'wss' or 'https'. ```swift public var isTLSScheme: Bool ``` -------------------------------- ### FoundationSecurityError Enum Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/security.md Errors specific to FoundationSecurity. ```swift public enum FoundationSecurityError: Error { case invalidRequest } ``` -------------------------------- ### URLParts Structure Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Represents parsed components from a WebSocket URL. ```swift public struct URLParts { let port: Int let host: String let isTLS: Bool } ``` -------------------------------- ### HTTPServerHandler parse Method Source: https://github.com/daltoniam/starscream/blob/master/_autodocs/api-reference/http-handler.md Parses a client's WebSocket upgrade request. ```swift func parse(data: Data) ```