Skip to content

Commit fef2e29

Browse files
committed
New: copy of the websockets.md file for reference
1 parent 0946bf8 commit fef2e29

File tree

1 file changed

+134
-0
lines changed

1 file changed

+134
-0
lines changed

docs/advanced/websockets.es.md

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# WebSockets
2+
3+
[WebSockets](https://en.wikipedia.org/wiki/WebSocket) allow for two-way communication between a client and server. Unlike HTTP, which has a request and response pattern, WebSocket peers can send an arbitrary number of messages in either direction. Vapor's WebSocket API allows you to create both clients and servers that handle messages asynchronously.
4+
5+
## Server
6+
7+
WebSocket endpoints can be added to your existing Vapor application using the Routing API. Use the `webSocket` method like you would use `get` or `post`.
8+
9+
```swift
10+
app.webSocket("echo") { req, ws in
11+
// Connected WebSocket.
12+
print(ws)
13+
}
14+
```
15+
16+
WebSocket routes can be grouped and protected by middleware like normal routes.
17+
18+
In addition to accepting the incoming HTTP request, WebSocket handlers accept the newly established WebSocket connection. See below for more information on using this WebSocket to send and read messages.
19+
20+
## Client
21+
22+
To connect to a remote WebSocket endpoint, use `WebSocket.connect`.
23+
24+
```swift
25+
WebSocket.connect(to: "ws://echo.websocket.org", on: eventLoop) { ws in
26+
// Connected WebSocket.
27+
print(ws)
28+
}
29+
```
30+
31+
The `connect` method returns a future that completes when the connection is established. Once connected, the supplied closure will be called with the newly connected WebSocket. See below for more information on using this WebSocket to send and read messages.
32+
33+
## Messages
34+
35+
The `WebSocket` class has methods for sending and receiving messages as well as listening for events like closure. WebSockets can transmit data via two protocols: text and binary. Text messages are interpreted as UTF-8 strings while binary data is interpreted as an array of bytes.
36+
37+
### Sending
38+
39+
Messages can be sent using the WebSocket's `send` method.
40+
41+
```swift
42+
ws.send("Hello, world")
43+
```
44+
45+
Passing a `String` to this method results in a text message being sent. Binary messages can be sent by passing a `[UInt8]`.
46+
47+
```swift
48+
ws.send([1, 2, 3])
49+
```
50+
51+
Message sending is asynchronous. You can supply an `EventLoopPromise` to the send method to be notified when the message has finished sending or failed to send.
52+
53+
```swift
54+
let promise = eventLoop.makePromise(of: Void.self)
55+
ws.send(..., promise: promise)
56+
promise.futureResult.whenComplete { result in
57+
// Succeeded or failed to send.
58+
}
59+
```
60+
61+
If using `async`/`await` you can use `await` to wait for the asynchronous operation to complete
62+
63+
```swift
64+
try await ws.send(...)
65+
```
66+
67+
### Receiving
68+
69+
Incoming messages are handled via the `onText` and `onBinary` callbacks.
70+
71+
```swift
72+
ws.onText { ws, text in
73+
// String received by this WebSocket.
74+
print(text)
75+
}
76+
77+
ws.onBinary { ws, binary in
78+
// [UInt8] received by this WebSocket.
79+
print(binary)
80+
}
81+
```
82+
83+
The WebSocket itself is supplied as the first parameter to these callbacks to prevent reference cycles. Use this reference to take action on the WebSocket after receiving data. For example, to send a reply:
84+
85+
```swift
86+
// Echoes received messages.
87+
ws.onText { ws, text in
88+
ws.send(text)
89+
}
90+
```
91+
92+
## Closing
93+
94+
To close a WebSocket, call the `close` method.
95+
96+
```swift
97+
ws.close()
98+
```
99+
100+
This method returns a future that will be completed when the WebSocket has closed. Like `send`, you may also pass a promise to this method.
101+
102+
```swift
103+
ws.close(promise: nil)
104+
```
105+
106+
Or `await` on it if using `async`/`await`:
107+
108+
```swift
109+
try await ws.close()
110+
```
111+
112+
To be notified when the peer closes the connection, use `onClose`. This future will be completed when either the client or server closes the WebSocket.
113+
114+
```swift
115+
ws.onClose.whenComplete { result in
116+
// Succeeded or failed to close.
117+
}
118+
```
119+
120+
The `closeCode` property is set when the WebSocket closes. This can be used to determine why the peer closed the connection.
121+
122+
## Ping / Pong
123+
124+
Ping and pong messages are sent automatically by the client and server to keep WebSocket connections alive. Your application can listen for these events using the `onPing` and `onPong` callbacks.
125+
126+
```swift
127+
ws.onPing { ws in
128+
// Ping was received.
129+
}
130+
131+
ws.onPong { ws in
132+
// Pong was received.
133+
}
134+
```

0 commit comments

Comments
 (0)