A concrete implementation of a WebSocket client implemented by wrapping Apple's URLSessionWebSocketTask.
The public interface of WebSocket is a simple struct whose public methods are exposed as closures. The reason for this design is to make it easy to inject fake WebSockets into your code for testing purposes.
The actual implementation is SystemWebSocket, but this type is not publicly accessible. Instead, you can access it via WebSocket.system(url:) or WebSocket.system(request:). SystemWebSocket tries its best to mirror the documented behavior of web browsers' WebSocket. Please report any deviations as bugs.
WebSocket exposes a simple API and makes heavy use of Swift Concurrency.
To use WebSocket, add a dependency to your Package.swift file:
letpackage=Package(
dependencies:[.package(
url:"https://github.com/shareup/websocket-apple.git",
from:"4.0.0")])// `WebSocket` starts connecting to the specified `URL` immediately.
letsocket=WebSocket.system(url:url(49999))
// Wait for `WebSocket` to be ready to send and receive messages.
tryawait socket.open()
// Send a message to the server
tryawait socket.send(.text("hello"))
// Receive messages from the server
forawaitmessagein socket.messages {print(message)}tryawait socket.close()- In your Terminal, navigate to the
websocket-appledirectory - Run the tests using
swift test
This library includes code from WebSocketKit and SwiftNIO, the use of which depends on their licenses.