import Foundation
// Create a URLSession
let url = URL(string: "wss://example.com/socket")!
let urlSession = URLSession(configuration: .default)
// Create a WebSocket task
let webSocketTask = urlSession.webSocketTask(with: url)
// Function to receive messages
func receiveMessages() {
webSocketTask.receive { result in
switch result {
case .failure(let error):
print("WebSocket error: \(error)")
case .success(let message):
switch message {
case .string(let text):
print("Received text: \(text)")
case .data(let data):
print("Received data: \(data)")
@unknown default:
fatalError()
}
// Continue receiving messages
receiveMessages()
}
}
}
// Start the WebSocket connection
webSocketTask.resume()
receiveMessages()
// Sending a message
let message = URLSessionWebSocketTask.Message.string("Hello, WebSocket!")
webSocketTask.send(message) { error in
if let error = error {
print("Error sending message: \(error)")
} else {
print("Message sent!")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?