` para mensagens recebidas:
```html
-
+
-
+
```
-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`.
+Do JavaScript queremos três coisas:
+1. Abrir a conexão.
+2. No envio do formulário -- `socket.send(message)` para a mensagem.
+3. Em uma mensagem recebida -- acrescentá-la ao `div#messages`.
-Here's the code:
+Aqui está o código:
```js
let socket = new WebSocket("wss://javascript.info/article/websocket/chat/ws");
-// send message from the form
+// envia a mensagem do formulário
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
+// mensagem recebida - mostra a mensagem em 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.
+O código do lado do servidor está um pouco além do nosso escopo. Aqui vamos usar Node.js, mas você não é obrigado a isso. Outras plataformas também têm seus meios de trabalhar com WebSocket.
-The server-side algorithm will be:
+O algoritmo do lado do servidor vai ser:
-1. Create `clients = new Set()` -- a set of sockets.
-2. For each accepted websocket, add it to the set `clients.add(socket)` and set `message` event listener to get its messages.
-3. When a message is received: iterate over clients and send it to everyone.
-4. When a connection is closed: `clients.delete(socket)`.
+1. Cria `clients = new Set()` -- um conjunto de sockets.
+2. Para cada websocket aceito, adiciona ele ao conjunto `clients.add(socket)` e define o ouvinte de evento `message` para obter suas mensagens.
+3. Quando uma mensagem é recebida: percorre os clientes e a envia para todo mundo.
+4. Quando uma conexão é fechada: `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
+ // aqui só tratamos conexões websocket
+ // num projeto real teríamos algum outro código aqui para tratar requisições não 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); // o tamanho máximo da mensagem vai ser 50
for(let client of clients) {
client.send(message);
@@ -355,34 +355,34 @@ function onSocketConnect(ws) {
```
-Here's the working example:
+Aqui está o exemplo funcionando:
[iframe src="chat" height="100" zip]
-You can also download it (upper-right button in the iframe) and run it locally. Just don't forget to install [Node.js](https://nodejs.org/en/) and `npm install ws` before running.
+Você também pode baixá-lo (botão no canto superior direito do iframe) e rodá-lo localmente. Só não esqueça de instalar o [Node.js](https://nodejs.org/en/) e `npm install ws` antes de rodar.
-## Summary
+## Resumo
-WebSocket is a modern way to have persistent browser-server connections.
+WebSocket é uma forma moderna de ter conexões persistentes entre navegador e servidor.
-- WebSockets don't have cross-origin limitations.
-- They are well-supported in browsers.
-- Can send/receive strings and binary data.
+- WebSockets não têm limitações cross-origin.
+- Eles têm bom suporte nos navegadores.
+- Podem enviar/receber strings e dados binários.
-The API is simple.
+A API é simples.
-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.
+O WebSocket por si só não inclui reconexão, autenticação e muitos outros mecanismos de alto nível. Então existem bibliotecas de cliente/servidor para isso, e também é possível implementar essas capacidades manualmente.
-Sometimes, to integrate WebSocket into existing projects, people run a 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 the WebSocket server, while `https://site.com` goes to the main HTTP-server.
+Às vezes, para integrar o WebSocket em projetos existentes, as pessoas rodam um servidor WebSocket em paralelo com o servidor HTTP principal, e eles compartilham um único banco de dados. Requisições para o WebSocket usam `wss://ws.site.com`, um subdomínio que leva ao servidor WebSocket, enquanto `https://site.com` vai para o servidor HTTP principal.
-Surely, other ways of integration are also possible.
+Com certeza, outras formas de integração também são possíveis.
diff --git a/5-network/11-websocket/chat.view/index.html b/5-network/11-websocket/chat.view/index.html
index 3dd4c24cd..f0520c866 100644
--- a/5-network/11-websocket/chat.view/index.html
+++ b/5-network/11-websocket/chat.view/index.html
@@ -1,7 +1,7 @@
@@ -9,12 +9,12 @@