You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[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.
3
+
[WebSockets](https://en.wikipedia.org/wiki/WebSocket)permiten la comunicación bidireccional entre un cliente y un servidor. A diferencia de HTTP, que tiene un patrón de solicitud y respuesta, los pares de WebSocket pueden enviar una cantidad arbitraria de mensajes en cualquier dirección. La API WebSocket de Vapor te permite crear tanto clientes como servidores que manejan mensajes de forma asincrónica.
4
4
5
-
## Server
5
+
## Servidor
6
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`.
7
+
Los endpoints de WebSocket se pueden agregar a tu aplicación Vapor existente mediante la API de enrutamiento. Usa el método `webSocket`como usarías `get`o`post`.
8
8
9
9
```swift
10
10
app.webSocket("echo") { req, ws in
@@ -13,122 +13,123 @@ app.webSocket("echo") { req, ws in
13
13
}
14
14
```
15
15
16
-
WebSocket routes can be grouped and protected by middleware like normal routes.
16
+
Las rutas de WebSocket se pueden agrupar y proteger mediante middleware como las rutas normales.
17
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.
18
+
Además de aceptar la solicitud HTTP entrante, los controladores de WebSocket aceptan la conexión WebSocket recién establecida. Consulta a continuación para obtener más información sobre el uso de este WebSocket para enviar y leer mensajes.
19
19
20
-
## Client
20
+
## Cliente
21
21
22
-
To connect to a remote WebSocket endpoint, use `WebSocket.connect`.
22
+
Para conectarse a un endpoint remoto de WebSocket, use `WebSocket.connect`.
23
23
24
24
```swift
25
25
WebSocket.connect(to: "ws://echo.websocket.org", on: eventLoop) { ws in
26
-
//Connected WebSocket.
26
+
// WebSocket conectado.
27
27
print(ws)
28
28
}
29
29
```
30
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.
31
+
El método `connect`devuelve un futuro que se completa cuando se establece la conexión. Una vez conectado, se llamará al closure proporcionado con el WebSocket recién conectado. Mira más información a continuación sobre el uso de este WebSocket para enviar y leer mensajes.
32
32
33
-
## Messages
33
+
## Mensajes
34
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.
35
+
La clase `WebSocket`tiene métodos para enviar y recibir mensajes, así como para escuchar eventos como el closure. Los WebSockets pueden transmitir datos a través de dos protocolos: texto y binario. Los mensajes de texto se interpretan como cadenas UTF-8, mientras que los datos binarios se interpretan como una matriz de bytes.
36
36
37
-
### Sending
37
+
### Envío
38
38
39
-
Messages can be sent using the WebSocket's `send`method.
39
+
Los mensajes se pueden enviar utilizando el método `send`de WebSocket.
40
40
41
41
```swift
42
42
ws.send("Hello, world")
43
43
```
44
44
45
-
Passing a`String`to this method results in a text message being sent. Binary messages can be sent by passing a`[UInt8]`.
45
+
Pasar una`String`a este método da como resultado el envío de un mensaje de texto. Los mensajes binarios se pueden enviar pasando un`[UInt8]`.
46
46
47
47
```swift
48
48
ws.send([1, 2, 3])
49
49
```
50
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.
51
+
El envío de mensajes es asincrónico. Puede proporcionar un `EventLoopPromise`al método de envío para recibir una notificación cuando el mensaje haya terminado de enviarse o falle en el envío.
52
52
53
53
```swift
54
54
let promise = eventLoop.makePromise(of: Void.self)
55
55
ws.send(..., promise: promise)
56
56
promise.futureResult.whenComplete { result in
57
-
//Succeeded or failed to send.
57
+
//Envío exitoso o fallido.
58
58
}
59
59
```
60
60
61
-
If using`async`/`await` you can use `await`to wait for the asynchronous operation to complete
61
+
Si usas`async`/`await`, puedes usar `await`para esperar a que se complete la operación asincrónica
62
62
63
63
```swift
64
64
tryawait ws.send(...)
65
65
```
66
66
67
-
### Receiving
67
+
### Recepción
68
68
69
-
Incoming messages are handled via the `onText`and`onBinary` callbacks.
69
+
Los mensajes entrantes se manejan a través de los callbacks `onText`y`onBinary`.
70
70
71
71
```swift
72
72
ws.onText { ws, text in
73
-
//String received by this WebSocket.
73
+
//Cadena recibida por este WebSocket.
74
74
print(text)
75
75
}
76
76
77
77
ws.onBinary { ws, binary in
78
-
// [UInt8] received by this WebSocket.
78
+
// [UInt8] recibido por este WebSocket.
79
79
print(binary)
80
80
}
81
81
```
82
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:
83
+
El propio WebSocket se proporciona como el primer parámetro de estos callbacks para evitar ciclos de referencia. Usa esta referencia para realizar una acción en el WebSocket después de recibir datos. Por ejemplo, para enviar una respuesta:
84
84
85
85
```swift
86
-
//Echoes received messages.
86
+
//Se hace eco de los mensajes recibidos.
87
87
ws.onText { ws, text in
88
88
ws.send(text)
89
89
}
90
90
```
91
91
92
-
## Closing
92
+
## Cierre
93
93
94
-
To close a WebSocket, call the `close` method.
94
+
Para cerrar un WebSocket, llama al método `close`.
95
95
96
96
```swift
97
97
ws.close()
98
98
```
99
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.
100
+
Este método devuelve un futuro que se completará cuando el WebSocket se haya cerrado. Al igual que `send`, también puede pasar una promesa a este método.
101
101
102
102
```swift
103
103
ws.close(promise: nil)
104
104
```
105
105
106
-
Or`await`on it if using`async`/`await`:
106
+
O`await`si usas`async`/`await`:
107
107
108
108
```swift
109
109
tryawait ws.close()
110
110
```
111
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.
112
+
Para recibir una notificación cuando el par cierra la conexión, utiliza`onClose`. Este futuro se completará cuando el cliente o el servidor cierren el WebSocket.
113
113
114
114
```swift
115
115
ws.onClose.whenComplete { result in
116
-
//Succeeded or failed to close.
116
+
//Cierre exitoso o fallido.
117
117
}
118
118
```
119
119
120
-
The `closeCode`property is set when the WebSocket closes. This can be used to determine why the peer closed the connection.
120
+
La propiedad `closeCode`se establece cuando el WebSocket se cierra. Esto se puede utilizar para determinar por qué el par cerró la conexión.
121
121
122
122
## Ping / Pong
123
123
124
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
+
El cliente y el servidor envían automáticamente mensajes de ping y pong para mantener activas las conexiones WebSocket. Su aplicación puede escuchar estos eventos mediante los callbacks `onPing` y `onPong`.
0 commit comments