### Async/Await WebSocket Connection and Messaging Source: https://context7.com/vapor/websocket-kit/llms.txt Demonstrates establishing a WebSocket connection and handling messages using Swift's async/await syntax. Supports sending text, binary data, and closing the connection. ```swift import WebSocketKit import NIOCore import NIOPosix let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) // Async connection try await WebSocket.connect( to: "ws://localhost:8080/chat", on: eventLoopGroup ) { ws in // Async text handler ws.onText { ws, text in print("Received: \(text)") try await ws.send("Echo: \(text)") } // Async binary handler ws.onBinary { ws, buffer in print("Received \(buffer.readableBytes) bytes") } // Send messages with async/await try await ws.send("Hello from async client!") try await ws.send([0x01, 0x02, 0x03]) // Binary data // Close connection try await ws.close(code: .normalClosure) } ``` -------------------------------- ### Connect to WebSocket Server (URL String) Source: https://context7.com/vapor/websocket-kit/llms.txt Establishes a client connection to a WebSocket server using a URL string. Handles incoming text messages and provides completion callbacks for connection status. ```swift import WebSocketKit import NIOCore import NIOPosix let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) // Connect using URL string WebSocket.connect(to: "ws://localhost:8080/chat", on: eventLoopGroup) { ws in print("Connected to WebSocket server") // Handle incoming text messages ws.onText { ws, text in print("Received: \(text)") } // Send a message ws.send("Hello, server!") }.whenComplete { result in switch result { case .success: print("Connection closed normally") case .failure(let error): print("Connection failed: \(error)") } } ``` -------------------------------- ### Configure WebSocketClient with TLS and Limits Source: https://context7.com/vapor/websocket-kit/llms.txt Use WebSocketClient.Configuration to define TLS settings, frame size limits, and event loop management. Ensure proper cleanup using syncShutdown after the connection completes. ```swift import WebSocketKit import NIOSSL import NIOPosix let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 2) // Create TLS configuration for secure connections var tlsConfig = TLSConfiguration.makeClientConfiguration() tlsConfig.certificateVerification = .fullVerification // Configure client with custom settings var clientConfig = WebSocketClient.Configuration( tlsConfiguration: tlsConfig, maxFrameSize: 1 << 16 // 64KB max frame size ) clientConfig.minNonFinalFragmentSize = 128 clientConfig.maxAccumulatedFrameCount = 100 clientConfig.maxAccumulatedFrameSize = 1 << 20 // 1MB max accumulated size // Create client instance let client = WebSocketClient( eventLoopGroupProvider: .shared(eventLoopGroup), configuration: clientConfig ) // Connect using the client client.connect( scheme: "wss", host: "secure.example.com", port: 443, path: "/ws", headers: ["Authorization": "Bearer token"] ) { ws in ws.onText { ws, text in print("Received: \(text)") } ws.send("Hello from configured client!") }.whenComplete { result in // Cleanup when done try? client.syncShutdown() } ``` -------------------------------- ### Connect to WebSocket Server (URI Components) Source: https://context7.com/vapor/websocket-kit/llms.txt Connects to a WebSocket server using individual URI components like scheme, host, port, path, and query parameters. Supports custom headers and TLS configuration. ```swift WebSocket.connect( scheme: "wss", host: "example.com", port: 443, path: "/api/websocket", query: "token=abc123", headers: ["Authorization": "Bearer token123"], configuration: .init(tlsConfiguration: .makeClientConfiguration()), on: eventLoopGroup ) { ws in ws.onText { ws, message in print("Received: \(message)") } } ``` -------------------------------- ### Implement Server-Side WebSocket Handler Source: https://context7.com/vapor/websocket-kit/llms.txt Configure a NIO ServerBootstrap with an NIOWebSocketServerUpgrader to handle WebSocket upgrades and message processing. Use the WebSocket.server method to manage the connection lifecycle. ```swift import NIOCore import NIOPosix import NIOHTTP1 import NIOWebSocket import WebSocketKit let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) // Create WebSocket server using ServerBootstrap let server = try ServerBootstrap(group: group) .childChannelInitializer { channel in let webSocketUpgrader = NIOWebSocketServerUpgrader( shouldUpgrade: { channel, req in // Validate upgrade request return channel.eventLoop.makeSucceededFuture([:]) }, upgradePipelineHandler: { channel, req in // Configure channel as WebSocket server return WebSocket.server(on: channel) { ws in print("Client connected from: \(channel.remoteAddress?.description ?? "unknown")") ws.onText { ws, text in print("Server received: \(text)") // Echo back to client ws.send("Server echo: \(text)") } ws.onBinary { ws, buffer in // Process binary data ws.send(buffer) } ws.onClose.whenComplete { _ in print("Client disconnected") } // Send welcome message ws.send("Welcome to the WebSocket server!") } } ) return channel.pipeline.configureHTTPServerPipeline( withServerUpgrade: ( upgraders: [webSocketUpgrader], completionHandler: { ctx in } ) ) } .bind(host: "localhost", port: 8080) .wait() print("WebSocket server running on port 8080") try server.closeFuture.wait() ``` -------------------------------- ### Send Text and Binary Messages with Callbacks Source: https://context7.com/vapor/websocket-kit/llms.txt Shows how to send text and binary messages over a WebSocket connection, including options for fire-and-forget sending and using completion promises for confirmation. ```swift WebSocket.connect(to: "ws://localhost:8080", on: eventLoopGroup) { ws in // Send text message (fire and forget) ws.send("Hello, World!") // Send text with completion promise let textPromise = ws.eventLoop.makePromise(of: Void.self) ws.send("Important message", promise: textPromise) textPromise.futureResult.whenComplete { result in switch result { case .success: print("Text message sent successfully") case .failure(let error): print("Failed to send: \(error)") } } // Send binary data let binaryData: [UInt8] = [0x00, 0x01, 0x02, 0x03, 0xFF] ws.send(binaryData) // Send Data object let data = Data([0x48, 0x65, 0x6C, 0x6C, 0x6F]) ws.send(data) // Send ByteBuffer directly var buffer = ByteBufferAllocator().buffer(capacity: 256) buffer.writeString("Binary content") ws.send(buffer, opcode: .binary) } ``` -------------------------------- ### Handle WebSocket Messages with Callbacks Source: https://context7.com/vapor/websocket-kit/llms.txt Use onText and onBinary to process incoming messages and enable bidirectional communication. ```swift WebSocket.connect(to: "ws://localhost:8080", on: eventLoopGroup) { ws in // Handle incoming text messages ws.onText { ws, text in print("Received text: \(text)") // Echo the message back ws.send("Echo: \(text)") // Close on specific command if text == "quit" { ws.close(promise: nil) } } // Handle incoming binary messages ws.onBinary { ws, buffer in print("Received \(buffer.readableBytes) bytes") // Process binary data if let bytes = buffer.getBytes(at: buffer.readerIndex, length: buffer.readableBytes) { print("Binary data: \(bytes)") } // Send binary response ws.send([0x01, 0x02, 0x03]) } // Initiate communication ws.send("Client connected") } ``` -------------------------------- ### Perform Raw Frame Transmission Source: https://context7.com/vapor/websocket-kit/llms.txt Use send(raw:opcode:fin:promise:) for low-level control, including custom opcodes and message fragmentation. ```swift WebSocket.connect(to: "ws://localhost:8080", on: eventLoopGroup) { ws in // Send a complete text frame let textData = "Hello".data(using: .utf8)! ws.send(raw: textData, opcode: .text, fin: true) // Send fragmented message (large payload split across frames) let largeMessage = "This is a very long message that will be split" let part1 = Data(largeMessage.prefix(20).utf8) let part2 = Data(largeMessage.dropFirst(20).prefix(15).utf8) let part3 = Data(largeMessage.dropFirst(35).utf8) // First fragment (fin: false) ws.send(raw: part1, opcode: .text, fin: false) // Continuation fragments ws.send(raw: part2, opcode: .continuation, fin: false) // Final fragment (fin: true) ws.send(raw: part3, opcode: .continuation, fin: true) // Send ByteBuffer with custom opcode var buffer = ByteBufferAllocator().buffer(capacity: 100) buffer.writeBytes([0x01, 0x02, 0x03]) ws.send(buffer, opcode: .binary, fin: true) } ``` -------------------------------- ### Connect via HTTP and HTTPS Proxy Source: https://context7.com/vapor/websocket-kit/llms.txt Establish WebSocket connections through proxy servers by providing proxy host, port, and authentication headers. Supports both plain and secure WebSocket schemes. ```swift let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) // Connect through HTTP proxy (plain WebSocket) WebSocket.connect( scheme: "ws", host: "target-server.com", port: 80, path: "/websocket", headers: [:], proxy: "proxy.company.com", proxyPort: 8080, proxyHeaders: ["Proxy-Authorization": "Basic dXNlcjpwYXNz"], proxyConnectDeadline: .now() + .seconds(30), on: eventLoopGroup ) { ws in ws.onText { ws, text in print("Via proxy: \(text)") } ws.send("Connected through proxy!") } // Connect through HTTPS proxy (secure WebSocket) var tlsConfig = TLSConfiguration.makeClientConfiguration() let client = WebSocketClient( eventLoopGroupProvider: .shared(eventLoopGroup), configuration: .init(tlsConfiguration: tlsConfig) ) client.connect( scheme: "wss", host: "secure-target.com", port: 443, path: "/api/stream", proxy: "proxy.company.com", proxyPort: 3128, proxyHeaders: ["Proxy-Authorization": "Bearer proxy-token"], proxyConnectDeadline: .now() + .seconds(60) ) { ws in ws.send("Secure connection via proxy") } ``` -------------------------------- ### Manage Connection Health with Ping/Pong Source: https://context7.com/vapor/websocket-kit/llms.txt Configure automatic ping intervals and handle manual ping/pong operations to monitor connection status. ```swift WebSocket.connect(to: "ws://localhost:8080", on: eventLoopGroup) { ws in // Enable automatic ping every 30 seconds // If pong not received before next ping, connection closes automatically ws.pingInterval = .seconds(30) // Manual ping without data ws.sendPing() // Manual ping with payload data ws.sendPing(Data("health-check".utf8)) // Handle pong responses ws.onPong { ws, data in print("Received pong with \(data.readableBytes) bytes") } // Handle incoming pings (server automatically sends pong) ws.onPing { ws, data in print("Received ping from server") } // Async ping Task { try await ws.sendPing() try await ws.sendPing(Data("async-ping".utf8)) } } ``` -------------------------------- ### Close WebSocket Connections Source: https://context7.com/vapor/websocket-kit/llms.txt Initiate graceful shutdowns using the close method and monitor connection state via onClose and closeCode. ```swift WebSocket.connect(to: "ws://localhost:8080", on: eventLoopGroup) { ws in // Monitor close event ws.onClose.whenComplete { result in print("Connection closed") if let code = ws.closeCode { print("Close code: \(code)") } } // Check connection state if !ws.isClosed { ws.send("Still connected!") } // Close with default code (.goingAway) _ = ws.close() // Close with specific error code ws.close(code: .normalClosure, promise: nil) // Close with promise for completion notification let closePromise = ws.eventLoop.makePromise(of: Void.self) ws.close(code: .normalClosure, promise: closePromise) closePromise.futureResult.whenSuccess { print("Clean shutdown complete") } // Async close Task { try await ws.close(code: .normalClosure) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.