` for incoming messages:
```
-From JavaScript we want three things:
-1. Open the connection.
-2. On form submission -- `socket.send(message)` for the message.
-3. On incoming message -- append it to `div#messages`.
+De JavaScript queremos tres cosas:
+1. Abrir la conexión.
+2. Ante el "submit" del form, enviar `socket.send(message)` el mensaje.
+3. Al llegar un mensaje, agregarlo a `div#messages`.
-Here's the code:
+Aquí el código:
```js
let socket = new WebSocket("wss://javascript.info/article/websocket/chat/ws");
-// send message from the form
+// enviar el mensaje del form
document.forms.publish.onsubmit = function() {
let outgoingMessage = this.message.value;
@@ -306,7 +306,7 @@ document.forms.publish.onsubmit = function() {
return false;
};
-// message received - show the message in div#messages
+// mensaje recibido - muestra el mensaje en div#messages
socket.onmessage = function(event) {
let message = event.data;
@@ -316,14 +316,14 @@ socket.onmessage = function(event) {
}
```
-Server-side code is a little bit beyond our scope. Here we'll use Node.js, but you don't have to. Other platforms also have their means to work with WebSocket.
+El código de servidor está algo fuera de nuestro objetivo. Aquí usaremos Node.js, pero no necesitas hacerlo. Otras plataformas también tienen sus formas de trabajar con WebSocket.
-The server-side algorithm will be:
+El algoritmo de lado de servidor será:
-1. Create `clients = new Set()` -- a set of sockets.
-2. For each accepted websocket, add it to the set `clients.add(socket)` and setup `message` event listener to get its messages.
-3. When a message received: iterate over clients and send it to everyone.
-4. When a connection is closed: `clients.delete(socket)`.
+1. Crear `clients = new Set()` -- un conjunto de sockets.
+2. Para cada websocket aceptado, sumarlo al conjunto `clients.add(socket)` y establecer un "event listener" `message` para obtener sus mensajes.
+3. Cuando un mensaje es recibido: iterar sobre los clientes y enviarlo a todos ellos.
+4. Cuando una conexión se cierra: `clients.delete(socket)`.
```js
const ws = new require('ws');
@@ -332,8 +332,8 @@ const wss = new ws.Server({noServer: true});
const clients = new Set();
http.createServer((req, res) => {
- // here we only handle websocket connections
- // in real project we'd have some other code here to handle non-websocket requests
+ // aquí solo manejamos conexiones websocket
+ // en proyectos reales tendremos también algún código para manejar peticiones no websocket
wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onSocketConnect);
});
@@ -341,7 +341,7 @@ function onSocketConnect(ws) {
clients.add(ws);
ws.on('message', function(message) {
- message = message.slice(0, 50); // max message length will be 50
+ message = message.slice(0, 50); // la longitud máxima del mensaje será 50
for(let client of clients) {
client.send(message);
@@ -355,34 +355,34 @@ function onSocketConnect(ws) {
```
-Here's the working example:
+Aquí está el ejemplo funcionando:
[iframe src="chat" height="100" zip]
-You can also download it (upper-right button in the iframe) and run locally. Just don't forget to install [Node.js](https://nodejs.org/en/) and `npm install ws` before running.
+Puedes descargarlo (botón arriba/derecha en el iframe) y ejecutarlo localmente. No olvides instalar [Node.js](https://nodejs.org/en/) y `npm install ws` antes de hacerlo.
-## Summary
+## Resumen
-WebSocket is a modern way to have persistent browser-server connections.
+WebSocket es la forma moderna de tener conexiones persistentes entre navegador y servidor .
-- WebSockets don't have cross-origin limitations.
-- They are well-supported in browsers.
-- Can send/receive strings and binary data.
+- Los WebSockets no tienen limitaciones "cross-origin".
+- Están muy bien soportados en los navegadores.
+- Pueden enviar y recibir datos string y binarios.
-The API is simple.
+La API es simple.
-Methods:
+Métodos:
- `socket.send(data)`,
- `socket.close([code], [reason])`.
-Events:
+Eventos:
- `open`,
- `message`,
- `error`,
- `close`.
-WebSocket by itself does not include reconnection, authentication and many other high-level mechanisms. So there are client/server libraries for that, and it's also possible to implement these capabilities manually.
+El WebSocket por sí mismo no incluye reconexión, autenticación ni otros mecanismos de alto nivel. Hay librerías cliente/servidor para eso, y también es posible implementar esas capacidades manualmente.
-Sometimes, to integrate WebSocket into existing project, people run WebSocket server in parallel with the main HTTP-server, and they share a single database. Requests to WebSocket use `wss://ws.site.com`, a subdomain that leads to WebSocket server, while `https://site.com` goes to the main HTTP-server.
+A veces, para integrar WebSocket a un proyecto existente, se ejecuta un servidor WebSocket en paralelo con el servidor HTTP principal compartiendo la misma base de datos. Las peticiones a WebSocket usan `wss://ws.site.com`, un subdominio que se dirige al servidor de WebSocket mientras que `https://site.com` va al servidor HTTP principal.
-Surely, other ways of integration are also possible.
+Seguro, otras formas de integración también son posibles.