|
2 | 2 |
|
3 | 3 | ## _(macOS, iOS, iPadOS, tvOS, and watchOS)_ |
4 | 4 |
|
5 | | -A concrete implementation of a WebSocket client implemented by wrapping Apple's `URLSessionWebSocketTask` and conforming to [`WebSocketProtocol`](https://github.com/shareup/websocket-protocol). `WebSocket` exposes a simple API and conforms to Apple's Combine [`Publisher`](https://developer.apple.com/documentation/combine/publisher). |
| 5 | +A concrete implementation of a WebSocket client implemented by wrapping Apple's [`NWConnection`](https://developer.apple.com/documentation/network/nwconnection). |
| 6 | + |
| 7 | +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 `WebSocket`s into your code for testing purposes. |
| 8 | + |
| 9 | +The actual implementation is `SystemWebSocket`, but this type is not publicly accessible. Instead, you can access it via `WebSocket.system(url:)`. `SystemWebSocket` tries its best to mirror the documented behavior of web browsers' [`WebSocket`](http://developer.mozilla.org/en-US/docs/Web/API/WebSocket). Please report any deviations as bugs. |
| 10 | + |
| 11 | +`WebSocket` exposes a simple API, makes heavy use of [Swift Concurrency](https://developer.apple.com/documentation/swift/swift_standard_library/concurrency), and conforms to Apple's Combine [`Publisher`](https://developer.apple.com/documentation/combine/publisher). |
6 | 12 |
|
7 | 13 | ## Usage |
8 | 14 |
|
9 | 15 | ```swift |
10 | | -let socket = WebSocket(url: url(49999)) |
11 | | - |
12 | | -let sub = socket.sink( |
13 | | - receiveCompletion: { print("Socket closed: \(String(describing: $0))") }, |
14 | | - receiveValue: { (result) in |
15 | | - switch result { |
16 | | - case .success(.open): |
17 | | - socket.send("First message") |
18 | | - case .success(.string(let incoming)): |
19 | | - print("Received \(incoming)") |
20 | | - case .failure: |
21 | | - socket.close() |
22 | | - default: |
23 | | - break |
24 | | - } |
25 | | - } |
26 | | -) |
27 | | -defer { sub.cancel() } |
28 | | - |
29 | | -socket.connect() |
| 16 | +// `WebSocket` starts connecting to the specified `URL` immediately. |
| 17 | +let socket = WebSocket.system(url: url(49999)) |
| 18 | + |
| 19 | +// Wait for `WebSocket` to be ready to send and receive messages. |
| 20 | +try await socket.open() |
| 21 | + |
| 22 | +// Send a message to the server |
| 23 | +try await socket.send(.text("hello")) |
| 24 | + |
| 25 | +// Receive messages from the server |
| 26 | +for await message in socket.messages { |
| 27 | + print(message) |
| 28 | +} |
| 29 | + |
| 30 | +try await socket.close() |
30 | 31 | ``` |
31 | 32 |
|
32 | 33 | ## Tests |
|
0 commit comments