Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebSocket DataChannel #11

Open
mattmassicotte opened this issue Jan 16, 2024 · 0 comments
Open

WebSocket DataChannel #11

mattmassicotte opened this issue Jan 16, 2024 · 0 comments

Comments

@mattmassicotte
Copy link
Contributor

Suggested implementation from @jbromburg:

extension DataChannel {
    static func socket(url: URL) throws -> DataChannel {
        let socketSession: URLSession = .init(configuration: .default)
        let socket: URLSessionWebSocketTask = socketSession.webSocketTask(with: url)
        
        socket.resume()
        
        let (stream, continuation) = DataSequence.makeStream()

        Task {
            while socket.state == .running {
                do {
                    let message = try await socket.receive()
                    switch message {
                    case .data(let data):
                        continuation.yield(data)
                    case .string(let string):
                        if let data = string.data(using: .utf8) {
                            continuation.yield(data)
                        }
                    @unknown default:
                        fatalError("Unhandled message type")
                    }
                } catch {
                    continuation.finish()
                    throw error
                }
            }
        }
        
        let writeHandler: DataChannel.WriteHandler = {
            try await socket.send(.data($0))
        }
        
        return DataChannel(writeHandler: writeHandler, dataSequence: stream)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant