aboutsummaryrefslogtreecommitdiff
path: root/files/pt-pt/web/api/websockets_api
diff options
context:
space:
mode:
authorRyan Johnson <rjohnson@mozilla.com>2021-04-29 16:16:42 -0700
committerGitHub <noreply@github.com>2021-04-29 16:16:42 -0700
commit95aca4b4d8fa62815d4bd412fff1a364f842814a (patch)
tree5e57661720fe9058d5c7db637e764800b50f9060 /files/pt-pt/web/api/websockets_api
parentee3b1c87e3c8e72ca130943eed260ad642246581 (diff)
downloadtranslated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.gz
translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.bz2
translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.zip
remove retired locales (#699)
Diffstat (limited to 'files/pt-pt/web/api/websockets_api')
-rw-r--r--files/pt-pt/web/api/websockets_api/index.html113
-rw-r--r--files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html221
-rw-r--r--files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html181
-rw-r--r--files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html442
-rw-r--r--files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html258
5 files changed, 0 insertions, 1215 deletions
diff --git a/files/pt-pt/web/api/websockets_api/index.html b/files/pt-pt/web/api/websockets_api/index.html
deleted file mode 100644
index 5fa4e252e2..0000000000
--- a/files/pt-pt/web/api/websockets_api/index.html
+++ /dev/null
@@ -1,113 +0,0 @@
----
-title: WebSocket API (WebSockets)
-slug: Web/API/WebSockets_API
-tags:
- - API
- - Client
- - Comunicação
- - Servidor
- - Sumario
- - Two-Way
- - WebSocket
- - WebSocket API
- - WebSockets
- - dados
- - interativo
-translation_of: Web/API/WebSockets_API
----
-<p>{{DefaultAPISidebar("Websockets API")}}</p>
-
-<p>A <strong>WebSocket API</strong> é uma tecnologia que permite abrir uma sessão de comunicação interativa bidirecional entre o navegador do utilizador e um servidor. Com esta API, é possível enviar mensagens para um servidor e receber respostas orientadas por eventos sem ter de sondar o servidor para obter uma resposta.</p>
-
-<div class="blockIndicator note">
-<p><strong>Nota:</strong> Enquanto a conexão WebSocket é funcionalmente semelhante aos <em>sockets</em> de estilo Unix, não são relacionados.</p>
-</div>
-
-<h2 id="Interfaces">Interfaces</h2>
-
-<dl>
- <dt><a href="/pt-PT/docs/Web/API/WebSocket"><code>WebSocket</code></a></dt>
- <dd>A interface principal para fazer conexão a um servidor de WebSocket e depois enviar e receber dados na mesma conexão.</dd>
- <dt><code><a href="/pt-PT/docs/Web/API/CloseEvent">CloseEvent</a></code></dt>
- <dd>O evento enviado pelo objeto WebSocket quando a conexão termina.</dd>
- <dt><a href="/pt-PT/docs/Web/API/MessageEvent"><code>MessageEvent</code></a></dt>
- <dd>O evento enviado pelo objeto WebSocket quando uma mensagem é recebida do servidor.</dd>
-</dl>
-
-<h2 id="Guias">Guias</h2>
-
-<ul>
- <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_aplicação_cliente_de_WebSocket">Escrever aplicação cliente de WebSocket </a></li>
- <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_servidores_de_WebSocket">Escrever servidores de WebSocket </a></li>
- <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_C%23">Escrever um servidor WebSocket em C#</a></li>
- <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_Java">Escrever um servidor WebSocket em Java</a></li>
-</ul>
-
-<h2 id="Tools" name="Tools">Ferramentas</h2>
-
-<ul>
- <li><a href="https://hacks.mozilla.org/2017/06/introducing-humblenet-a-cross-platform-networking-library-that-works-in-the-browser/">HumbleNet</a>: Uma biblioteca em rede multi-plataformas que funciona no navegador. Consiste num wrapper em C em torno de WebSockets e WebRTC que abstrai as diferenças entre navegadores, facilitando a criação de funcionalidades de rede multi-utilizador para jogos e outras aplicações.</li>
- <li><a href="https://github.com/uWebSockets/uWebSockets">µWebSockets</a>: Implementação de servidor e cliente WebSocket altamente escalável para <a href="https://isocpp.org/">C++11</a> e <a href="https://nodejs.org">Node.js</a>.</li>
- <li><a href="https://github.com/ClusterWS/ClusterWS">ClusterWS</a>:  Framework leve, rápida e poderosa para construir aplicações WebSocket escaláveis no <a href="https://nodejs.org">Node.js</a>.</li>
- <li><a href="https://github.com/ClusterWS/cWS">CWS</a>: Implementação rápida WebSocket de C++ para Node.js (uWebSockets v0.14 fork)</li>
- <li><a class="external" href="https://socket.io">Socket.IO</a>: Um protocolo de transferência de terceiros, baseado em long polling/WebSocket para <a href="https://nodejs.org">Node.js</a>.</li>
- <li><a href="http://socketcluster.io/">SocketCluster</a>: Uma pub/sub WebSocket framework para <a href="https://nodejs.org">Node.js</a> com foco na escalabilidade.</li>
- <li><a class="link-https" href="https://github.com/Worlize/WebSocket-Node">WebSocket-Node</a>: Uma implementação da API de servidores WebSocket para <a href="https://nodejs.org">Node.js</a>.</li>
- <li><a href="http://www.totaljs.com">Total.js</a>: Uma <em>framework</em> de aplicações web para <a href="https://www.nodejs.org">Node.js</a> (Example: <a href="https://github.com/totaljs/examples/tree/master/websocket">WebSocket chat</a>)</li>
- <li><a href="https://www.npmjs.com/package/faye-websocket">Faye</a>: Uma <a href="/en-US/docs/Web/API/WebSockets_API">WebSocket</a> (ligações bidireccionais) e <a href="/en-US/docs/Web/API/EventSource/">EventSource</a> (ligações unidireccionais) para <a href="https://nodejs.org">Node.js</a> Server e Client.</li>
- <li><a href="http://signalr.net/">SignalR</a>: SignalR usa WebSockets quando está disponível, e discretamente volta para outras técnicas e tecnologias quando não está, enquanto o seu código de aplicação permanece o mesmo.</li>
- <li><a href="https://caddyserver.com/docs/websocket">Caddy</a>: Um servidor web capaz de substituir comandos arbitrários (stdin/stdout) com uma <em>web socket</em>.</li>
- <li><a href="https://github.com/websockets/ws">ws</a>: uma biblioteca de cliente e servidor WebSocket popular para <a href="https://nodejs.org/">Node.js</a>.</li>
- <li><a href="https://github.com/bigstepinc/jsonrpc-bidirectional">jsonrpc-bidirectional</a>: RPC assíncrono que, numa única ligação, pode ter funções exportadas no servidor e, e ao mesmo tempo, no cliente (cliente pode chamar servidor, servidor também pode chamar cliente).</li>
- <li><a href="https://github.com/ninenines/cowboy">cowboy</a>: Cowboy é um pequeno, rápido e moderno servidor HTTP para Erlang/OTP com suporte para WebSocket.</li>
-</ul>
-
-<h2 id="Related_Topics" name="Related_Topics">Tópicos Relacionados</h2>
-
-<ul>
- <li><a href="/pt-PT/docs/Web/Guide/AJAX">AJAX</a></li>
- <li><a href="/pt-PT/docs/Web/JavaScript">JavaScript</a></li>
-</ul>
-
-<h2 id="Especificações">Especificações</h2>
-
-<table class="standard-table">
- <thead>
- <tr>
- <th scope="col">Especificação</th>
- <th scope="col">Estado</th>
- <th scope="col">Comentário</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>{{SpecName("HTML WHATWG", "web-sockets.html", "WebSocket API")}}</td>
- <td>{{Spec2("HTML WHATWG")}}</td>
- <td></td>
- </tr>
- <tr>
- <td><a href="https://www.w3.org/TR/websockets/">WebSockets</a></td>
- <td><span class="spec-CR">Candidate Recommendation</span></td>
- <td></td>
- </tr>
- <tr>
- <td>{{RFC(6455, "The WebSocket Protocol")}}</td>
- <td><span class="spec-RFC">IETF RFC</span></td>
- <td></td>
- </tr>
- </tbody>
-</table>
-
-<h2 id="Compatibilidade">Compatibilidade</h2>
-
-
-
-<p>{{Compat("api.WebSocket")}}</p>
-
-<h2 id="Ver_também">Ver também</h2>
-
-<ul>
- <li><a class="external" href="http://tools.ietf.org/html/rfc6455">RFC 6455 — O Protocolo WebSocket</a></li>
- <li><a class="external" href="https://www.w3.org/TR/websockets/">Especificação da API WebSocket</a></li>
- <li><em><a href="/en-US/docs/Server-sent_events">Server-Sent Events</a></em></li>
-</ul>
diff --git a/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html b/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html
deleted file mode 100644
index d41f7c7b3e..0000000000
--- a/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html
+++ /dev/null
@@ -1,221 +0,0 @@
----
-title: Escrever um servidor WebSocket em Java
-slug: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java
-tags:
- - HTML5
- - Handshaking
- - Tutorial
- - WebSockets
-translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java
-original_slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_Java
----
-<h2 id="Introdução">Introdução</h2>
-
-<p>Este exemplo mostra-lhe como criar um servidor com API de WebSocket utilizando Oracle Java.<br>
- <br>
- Embora outras linguagens do lado do servidor possam ser utilizadas para criar um servidor WebSocket, este exemplo utiliza Oracle Java para simplificar o código do exemplo.</p>
-
-<p>Este servidor está em conformidade com o <a href="http://tools.ietf.org/html/rfc6455">RFC 6455</a>, pelo que apenas trata de ligações a partir das seguintes versões dos navegadores; Chrome 16, Firefox 11, IE 10 e superior.</p>
-
-<h2 id="Primeiros_passos">Primeiros passos</h2>
-
-<p>Os WebSockets comunicam através de uma ligação <em>{{interwiki("wikipedia", "Transmission_Control_Protocol", "TCP (Transmission Control Protocol)")}}</em>. A classe <a href="http://docs.oracle.com/javase/8/docs/api/java/net/ServerSocket.html">ServerSocket</a> do Java está localizada no pacote java.net.</p>
-
-<h3 id="ServerSocket">ServerSocket</h3>
-
-<h4 id="Construtor">Construtor</h4>
-
-<dl>
- <dt><code>ServerSocket(int port)</code></dt>
- <dd>Quando se instância a classe ServerSocket, esta é ligada ao número da porta que se especificou pelo argumento <code>port</code>.<br>
- <br>
- Aqui está uma implementação dividida em partes:</dd>
-</dl>
-
-<pre class="brush: java notranslate">import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Base64;
-import java.util.Scanner;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class WebSocket {
- public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
- ServerSocket server = new ServerSocket(80);
- try {
- System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection...");
- Socket client = server.accept();
- System.out.println("A client connected.");</pre>
-
-<h3 id="Socket">Socket</h3>
-
-<h4 id="Métodos">Métodos</h4>
-
-<dl>
- <dt><code><span class="memberNameLink"><a href="http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getInputStream--">getInputStream</a></span>()</code></dt>
- <dd>Devolve uma <em>input stream</em> para este socket.</dd>
- <dt><code><span class="memberNameLink"><a href="http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getOutputStream--">getOutputStream</a></span>()</code></dt>
- <dd>Devolve uma <em>output stream</em> para este socket.</dd>
-</dl>
-
-<h3 id="OutputStream">OutputStream</h3>
-
-<h4 id="Métodos_2">Métodos</h4>
-
-<dl>
- <dt><code>write(byte[] b, int off, int len)</code></dt>
- <dd>Escreve o número de bytes especificado por <code>len</code> a partir da matriz de bytes especificada por <code>b</code>, começando no índice indicado por <code>off</code> para este <em>output stream</em>.</dd>
-</dl>
-
-<h3 id="InputStream">InputStream</h3>
-
-<h4 id="Métodos_3">Métodos</h4>
-
-<dl>
- <dt><code><span class="brush: cpp" style="line-height: 1.572;">read</span>(byte[] b, int off, int len)</code></dt>
- <dd>Lê até um número de bytes especificado por <code>len</code> da matriz de bytes especificada por <code>b</code>, começando no índice indicado por <code>off</code> para este <em>input stream</em>.<em> </em></dd>
-</dl>
-
-<p>Vamos continuar o nosso exemplo.</p>
-
-<pre class="brush: java notranslate"> InputStream in = client.getInputStream();
- OutputStream out = client.getOutputStream();
- Scanner s = new Scanner(in, "UTF-8");</pre>
-
-<h2 id="Handshaking_aperto_de_mão"><em>Handshaking</em> (a<strong>perto de mão</strong>)</h2>
-
-<p>Quando um cliente se liga a um servidor, envia um pedido GET para actualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.</p>
-
-<pre class="brush: java notranslate"> try {
- String data = s.useDelimiter("\\r\\n\\r\\n").next();
- Matcher get = Pattern.compile("^GET").matcher(data);</pre>
-
-<p>Criar a resposta é mais fácil do que compreender porque o deve fazer desta forma.</p>
-
-<p>Você deve,</p>
-
-<ol>
- <li>Obter o valor do cabeçalho de pedido da <code>Sec-WebSocket-Key</code> sem qualquer espaço em branco</li>
- <li>Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"</li>
- <li>Calcule o código SHA-1 e Base64 do mesmo</li>
- <li>Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.</li>
-</ol>
-
-<pre class="brush: java notranslate"> if (get.find()) {
- Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
- match.find();
- byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n"
- + "Connection: Upgrade\r\n"
- + "Upgrade: websocket\r\n"
- + "Sec-WebSocket-Accept: "
- + Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
- + "\r\n\r\n").getBytes("UTF-8");
- out.write(response, 0, response.length);
-</pre>
-
-<h2 id="Descodificar_mensagens">Descodificar mensagens</h2>
-
-<p>Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.<br>
- <br>
- Se enviarmos "abcdef", recebemos estes bytes:</p>
-
-<table>
- <tbody>
- <tr>
- <td>129</td>
- <td>134</td>
- <td>167</td>
- <td>225</td>
- <td>225</td>
- <td>210</td>
- <td>198</td>
- <td>131</td>
- <td>130</td>
- <td>182</td>
- <td>194</td>
- <td>135</td>
- </tr>
- </tbody>
-</table>
-
-<h4 id="129_FIN_RSV1_RSV2_RSV3_opcode">129 (FIN, RSV1, RSV2, RSV3, <em>opcode</em>)</h4>
-
-<p>Pode enviar a sua mensagem em fragmentos, mas por enquanto o FIN é 1 indicando que a mensagem está toda num fragmento. RSV1, RSV2 e RSV3 são sempre 0, a não ser que um significado para os bytes é negociado. <em>Opcode</em> 0x1 significa que isto é um texto (ver <a href="http://tools.ietf.org/html/rfc6455#section-5.2">lista completa de <em>opcodes</em></a>).</p>
-
-<table>
- <thead>
- <tr>
- <th scope="col">FIN (É o último fragmento da mensagem?)</th>
- <th scope="col">RSV1</th>
- <th scope="col">RSV2</th>
- <th scope="col">RSV3</th>
- <th scope="col"><em>Opcode</em></th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>1</td>
- <td>0</td>
- <td>0</td>
- <td>0</td>
- <td>0x1=0001</td>
- </tr>
- </tbody>
-</table>
-
-<h4 id="134_comprimento_da_mensagem">134 (comprimento da mensagem)</h4>
-
-<p>O comprimento da mensagem é indicada das seguintes formas:</p>
-
-<ul>
- <li>Se o segundo byte menos 128 estiver entre 0 e 125, este é o comprimento da mensagem,</li>
- <li>Se o resultado é 126, os seguintes 2 bytes (inteiro de 16 bits sem assinatura) ditam o comprimento,</li>
- <li>E se o resultado é 127, os 8 bytes seguintes (64-bit inteiro não assinado, o bit mais significativo DEVE ser 0) são o comprimento.</li>
-</ul>
-
-<h4 id="167_225_225_e_210_chave_para_descodificar">167, 225, 225 e 210 (chave para descodificar)</h4>
-
-<p>Estes são os bytes da chave para descodificar. A chave muda para cada mensagem.</p>
-
-<h4 id="198_131_130_182_194_135_conteúdo_da_mensagem">198, 131, 130, 182, 194, 135 (conteúdo da mensagem)</h4>
-
-<p>Os restantes bytes codificados são a mensagem.</p>
-
-<h3 id="Algoritmo_para_descodificar">Algoritmo para descodificar</h3>
-
-<p>O algoritmo usado para descodificar a mensagem é o seguinte:</p>
-
-<p><em>D<sub>i</sub></em> = <em>E<sub>i</sub></em> XOR <em>M</em><sub>(<em>i</em> mod 4)</sub></p>
-
-<p>onde <em>D</em> é a série de bytes da mensagem descodificados, <em>E</em> é a série de bytes da mensagem codificados, <em>M</em> é a série de bytes da chave, e <em>i</em> é o índice do byte da mensagem a ser descodificado.</p>
-
-<p>Exemplo em Java:</p>
-
-<pre class="brush: java notranslate"> byte[] decoded = new byte[6];
- byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 };
- byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 };
- for (int i = 0; i &lt; encoded.length; i++) {
- decoded[i] = (byte) (encoded[i] ^ key[i &amp; 0x3]);
- }
- }
- } finally {
- s.close();
- }
- } finally {
- server.close();
- }
- }
-}</pre>
-
-<h2 id="Ver_também">Ver também</h2>
-
-<ul>
- <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_servidores_de_WebSocket">Escrever servidores de WebSocket</a></li>
-</ul>
-
-<div id="cke_pastebin"></div>
diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html
deleted file mode 100644
index 08b86ecca8..0000000000
--- a/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html
+++ /dev/null
@@ -1,181 +0,0 @@
----
-title: Escrever aplicação cliente de WebSocket
-slug: Web/API/WebSockets_API/Writing_WebSocket_client_applications
-tags:
- - Client
- - Exemplo
- - Guía
- - Networking
- - Web Sockets API
- - WebSocket
- - WebSocket API
- - WebSockets
-translation_of: Web/API/WebSockets_API/Writing_WebSocket_client_applications
-original_slug: Web/API/WebSockets_API/Escrever_aplicação_cliente_de_WebSocket
----
-<div>{{APIRef("Websockets API")}}</div>
-
-<p>WebSocket client applications use the <a href="/en-US/docs/Web/API/Websockets_API">WebSocket API</a> to communicate with <a href="/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers">WebSocket servers</a> using the WebSocket protocol.</p>
-
-<p>{{AvailableInWorkers}}</p>
-
-<div class="note">
-<p><strong>Note:</strong> The example snippets in this article are taken from our WebSocket chat client/server sample. <a href="https://github.com/mdn/samples-server/tree/master/s/websocket-chat">See the code</a>, then <a href="https://mdn-samples.mozilla.org/s/websocket-chat">try out the example for yourself</a>.</p>
-</div>
-
-<h2 id="Creating_a_WebSocket_object">Creating a WebSocket object</h2>
-
-<p>In order to communicate using the WebSocket protocol, you need to create a {{domxref("WebSocket")}} object; this will automatically attempt to open the connection to the server.</p>
-
-<p>The WebSocket constructor accepts one required and one optional parameter:</p>
-
-<pre class="syntaxbox notranslate"><em>webSocket</em> = new WebSocket(<em>url</em>, <em>protocols</em>);
-</pre>
-
-<dl>
- <dt><code>url</code></dt>
- <dd>The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme <code>wss://</code>, although some software may allow you to use the insecure <code>ws://</code> for local connections.</dd>
- <dt><code>protocols</code> {{ optional_inline() }}</dt>
- <dd>Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified <code>protocol</code>). If you don't specify a protocol string, an empty string is assumed.</dd>
-</dl>
-
-<p>The constructor will throw a <code>SecurityError</code> if the destination doesn't allow access. This may happen if you attempt to use an insecure connection (most {{Glossary("user agent", "user agents")}} now require a secure link for all WebSocket connections unless they're on the same device or possibly on the same network).</p>
-
-<h3 id="Connection_errors">Connection errors</h3>
-
-<p>If an error occurs while attempting to connect, first a simple event with the name <code>error</code> is sent to the {{domxref("WebSocket")}} object (thereby invoking its {{domxref("WebSocket.onerror", "onerror")}} handler), and then the {{domxref("CloseEvent")}} is sent to the <code>WebSocket</code> object (thereby invoking its {{domxref("WebSocket.onclose", "onclose")}} handler) to indicate the reason for the connection's closing.</p>
-
-<p>The browser may also output to its console a more descriptive error message as well as a closing code as defined in <a class="external" href="http://tools.ietf.org/html/rfc6455#section-7.4" title="RFC 6455 Section 7.4">RFC 6455, Section 7.4</a> through the {{domxref("CloseEvent")}}.</p>
-
-<h3 id="Examples">Examples</h3>
-
-<p>This simple example creates a new WebSocket, connecting to the server at <code><span class="nowiki">wss://www.example.com/socketserver</span></code>. A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted.</p>
-
-<pre class="brush: js notranslate">var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");
-</pre>
-
-<p>On return, {{domxref("WebSocket.readyState", "exampleSocket.readyState")}} is <code>CONNECTING</code>. The <code>readyState</code> will become <code>OPEN</code> once the connection is ready to transfer data.</p>
-
-<p>If you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols:</p>
-
-<pre class="brush: js notranslate">var exampleSocket = new WebSocket("wss://www.example.com/socketserver", ["protocolOne", "protocolTwo"]);
-</pre>
-
-<p>Once the connection is established (that is, <code>readyState</code> is <code>OPEN</code>), {{domxref("WebSocket.protocol", "exampleSocket.protocol")}} will tell you which protocol the server selected.</p>
-
-<p>Establishing a WebSocket relies on the <a href="/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism">HTTP Upgrade mechanism</a>, so the request for the protocol upgrade is implicit when we address the web server as <code><span class="nowiki">ws://www.example.com</span></code> or <code><span class="nowiki">wss://www.example.com</span></code>.</p>
-
-<h2 id="Sending_data_to_the_server">Sending data to the server</h2>
-
-<p>Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the <code>WebSocket</code> object's {{domxref("WebSocket.send", "send()")}} method for each message you want to send:</p>
-
-<pre class="brush: js notranslate">exampleSocket.send("Here's some text that the server is urgently awaiting!");
-</pre>
-
-<p>You can send data as a string, {{ domxref("Blob") }}, or {{jsxref("ArrayBuffer")}}.</p>
-
-<p>As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the <code>send()</code> method immediately after creating a WebSocket object will be successful. We can at least be sure that attempting to send data only takes place once a connection is established by defining an {{domxref("WebSocket.onopen", "onopen")}} event handler to do the work:</p>
-
-<pre class="brush: js notranslate">exampleSocket.onopen = function (event) {
- exampleSocket.send("Here's some text that the server is urgently awaiting!");
-};
-</pre>
-
-<h3 id="Using_JSON_to_transmit_objects">Using JSON to transmit objects</h3>
-
-<p>One handy thing you can do is use {{glossary("JSON")}} to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data:</p>
-
-<pre class="brush: js notranslate">// Send text to all users through the server
-function sendText() {
- // Construct a msg object containing the data the server needs to process the message from the chat client.
- var msg = {
- type: "message",
- text: document.getElementById("text").value,
- id: clientID,
- date: Date.now()
- };
-
- // Send the msg object as a JSON-formatted string.
- exampleSocket.send(JSON.stringify(msg));
-
- // Blank the text input element, ready to receive the next line of text from the user.
- document.getElementById("text").value = "";
-}
-</pre>
-
-<h2 id="Receiving_messages_from_the_server">Receiving messages from the server</h2>
-
-<p>WebSockets is an event-driven API; when messages are received, a <code>message</code> event is sent to the <code>WebSocket</code> object. To handle it, add an event listener for the <code>message</code> event, or use the {{domxref("WebSocket.onmessage", "onmessage")}} event handler. To begin listening for incoming data, you can do something like this:</p>
-
-<pre class="brush: js notranslate">exampleSocket.onmessage = function (event) {
- console.log(event.data);
-}
-</pre>
-
-<h3 id="Receiving_and_interpreting_JSON_objects">Receiving and interpreting JSON objects</h3>
-
-<p>Let's consider the chat client application first alluded to in {{ anch("Using JSON to transmit objects") }}. There are assorted types of data packets the client might receive, such as:</p>
-
-<ul>
- <li>Login handshake</li>
- <li>Message text</li>
- <li>User list updates</li>
-</ul>
-
-<p>The code that interprets these incoming messages might look like this:</p>
-
-<pre class="brush: js notranslate">exampleSocket.onmessage = function(event) {
- var f = document.getElementById("chatbox").contentDocument;
- var text = "";
- var msg = JSON.parse(event.data);
- var time = new Date(msg.date);
- var timeStr = time.toLocaleTimeString();
-
- switch(msg.type) {
- case "id":
- clientID = msg.id;
- setUsername();
- break;
- case "username":
- text = "&lt;b&gt;User &lt;em&gt;" + msg.name + "&lt;/em&gt; signed in at " + timeStr + "&lt;/b&gt;&lt;br&gt;";
- break;
- case "message":
- text = "(" + timeStr + ") &lt;b&gt;" + msg.name + "&lt;/b&gt;: " + msg.text + "&lt;br&gt;";
- break;
- case "rejectusername":
- text = "&lt;b&gt;Your username has been set to &lt;em&gt;" + msg.name + "&lt;/em&gt; because the name you chose is in use.&lt;/b&gt;&lt;br&gt;"
- break;
- case "userlist":
- var ul = "";
- for (i=0; i &lt; msg.users.length; i++) {
- ul += msg.users[i] + "&lt;br&gt;";
- }
- document.getElementById("userlistbox").innerHTML = ul;
- break;
- }
-
- if (text.length) {
- f.write(text);
- document.getElementById("chatbox").contentWindow.scrollByPages(1);
- }
-};
-</pre>
-
-<p>Here we use {{jsxref("JSON.parse()")}} to convert the JSON object back into the original object, then examine and act upon its contents.</p>
-
-<h3 id="Text_data_format">Text data format</h3>
-
-<p>Text received over a WebSocket connection is in UTF-8 format.</p>
-
-<h2 id="Closing_the_connection">Closing the connection</h2>
-
-<p>When you've finished using the WebSocket connection, call the WebSocket method {{domxref("WebSocket.close", "close()")}}:</p>
-
-<pre class="brush: js notranslate">exampleSocket.close();
-</pre>
-
-<p>It may be helpful to examine the socket's {{domxref("WebSocket.bufferedAmount", "bufferedAmount")}} attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network. If this value isn't 0, there's pending data still, so you may wish to wait before closing the connection.</p>
-
-<h2 id="Security_considerations">Security considerations</h2>
-
-<p>WebSockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure WebSocket connection from a page loaded using HTTPS or vice-versa. Most browsers now only allow secure WebSocket connections, and no longer support using them in insecure contexts.</p>
diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html
deleted file mode 100644
index a842c9d7d1..0000000000
--- a/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html
+++ /dev/null
@@ -1,442 +0,0 @@
----
-title: Escrever um servidor WebSocket em C#
-slug: Web/API/WebSockets_API/Writing_WebSocket_server
-tags:
- - HTML5
- - Tutorial
- - WebSockets
-translation_of: Web/API/WebSockets_API/Writing_WebSocket_server
-original_slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_C
----
-<h2 id="Introdução">Introdução</h2>
-
-<p>Se desejar utilizar o WebSocket API, é útil dispor de um servidor. Neste artigo pode ver como escrever um em C#. Pode fazê-lo em qualquer língua do lado do servidor, mas para manter as coisas simples e mais compreensíveis, vamos usar a linguagem da Microsoft.</p>
-
-<p>Este servidor está em conformidade com o <a href="http://tools.ietf.org/html/rfc6455">RFC 6455</a>, pelo que só tratará de ligações a partir das versões de navegadores; Chrome 16, Firefox 11, e IE 10 ou superior.</p>
-
-<h2 id="Primeiros_passos">Primeiros passos</h2>
-
-<p>Os WebSockets comunicam através de uma ligação interwiki("wikipedia","Transmission_Control_Protocol","TCP (Transmission Control Protocol)"). Felizmente, C# tem uma classe TcpListener que serve para escutar ligações de TCP. Encontra-se no espaço de nomes <code>System.Net.Sockets</code>.</p>
-
-<div class="note">
-<p><span style="line-height: 1.572;"><strong>Nota:</strong> É aconselhável incluir o namespace com <code>using</code> a fim de escrever menos. Permite a utilização das classes de um namespace sem escrever sempre o namespace completo.</span></p>
-</div>
-
-<h3 id="TcpListener">TcpListener</h3>
-
-<h4 id="Construtor">Construtor</h4>
-
-<dl>
- <dt><code>TcpListener(System.Net.IPAddress localaddr, int port)</code></dt>
- <dd><code>localaddr</code> indica o endereço IP do ouvinte e <code>port</code> indica a porta.</dd>
-</dl>
-
-<div class="note">
-<p><span style="line-height: 1.572;"><strong>Nota:</strong> Para criar um objeto <code>IPAddress</code> a partir de uma <code>string</code>, use o método <em>static</em> </span><code>Parse</code><span style="line-height: 1.572;"> de </span><code>IPAddress</code><em>.</em></p>
-</div>
-
-<h4 id="Métodos"><span style="line-height: 1.572;">Métodos</span></h4>
-
-<dl>
- <dt><code><span style="line-height: 1.572;">Start()</span></code></dt>
- <dd>Começa a escutar os pedidos de ligação recebidos.</dd>
-</dl>
-
-<dl>
- <dt><code><span style="line-height: 1.572;">AcceptTcpClient()</span></code></dt>
- <dd>Espera por uma ligação TCP, aceita-a e devolve-a como um objeto <a href="https://docs.microsoft.com/pt-pt/dotnet/api/system.net.sockets.tcpclient">TcpClient</a>.</dd>
-</dl>
-
-<h4 class="syntaxbox" id="Exemplo">Exemplo</h4>
-
-<p><span style="line-height: 1.572;">Aqui tem uma implementação básica do servidor:</span></p>
-
-<pre class="brush: cpp notranslate">​using System.Net.Sockets;
-using System.Net;
-using System;
-
-class Server {
- public static void Main() {
- TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
-
- server.Start();
- Console.WriteLine("O servidor começou com endreço 127.0.0.1:80.{0}Esperando por uma conexão...", Environment.NewLine);
-
- TcpClient client = server.AcceptTcpClient();
-
- Console.WriteLine("Um cliente está conectado.");
- }
-}
-</pre>
-
-<h3 id="TcpClient"><span style="line-height: 1.572;">TcpClient</span></h3>
-
-<h4 id="Métodos_2">Métodos</h4>
-
-<dl>
- <dt><code>GetStream()</code></dt>
- <dd>Obtém o <em>stream</em> que é o canal de comunicação. Ambos os lados do canal têm capacidade de leitura e escrita.</dd>
-</dl>
-
-<h4 id="Propriedades">Propriedades</h4>
-
-<dl>
- <dt><code>int Available</code></dt>
- <dd>Esta propriedade indica quantos bytes de dados foram enviados. O valor é zero até que a propriedade <code>NetworkStream.DataAvailable</code> seja <code>true</code>.</dd>
-</dl>
-
-<h3 id="NetworkStream">NetworkStream</h3>
-
-<h4 id="Métodos_3">Métodos</h4>
-
-<dl>
- <dt><code>Write(Byte[] buffer, int offset, int size)</code></dt>
- <dd>Escreve bytes vindos do <code>buffer</code>. <code>offset</code> e <code>size</code> determinam o comprimento da mensagem.</dd>
- <dt><code><span class="brush: cpp" style="line-height: 1.572;">Read(Byte[] buffer, int offset, int size)</span></code></dt>
- <dd><span class="brush: cpp" style="line-height: 1.572;">Lê bytes do <code>buffer</code>. <code>offset</code> e <code>size</code> </span>determinam o comprimento da mensagem<span class="brush: cpp" style="line-height: 1.572;">.</span></dd>
-</dl>
-
-<h4 id="Exemplo_2">Exemplo</h4>
-
-<p>Vamos continuar o nosso exemplo:</p>
-
-<pre class="brush: cpp notranslate">TcpClient client = server.AcceptTcpClient();
-
-Console.WriteLine("Um cliente está conectado.");
-
-NetworkStream stream = client.GetStream();
-
-// entrar num ciclo infinito para poder processar qualquer mudança no stream
-while (true) {
- while (!stream.DataAvailable);
-
- Byte[] bytes = new Byte[client.Available];
-
- stream.Read(bytes, 0, bytes.Length);
-}</pre>
-
-<h2 id="Handshaking_aperto_de_mão"><em>Handshaking </em>(aperto de mão)</h2>
-
-<p>Quando um cliente se liga a um servidor, envia um pedido GET para atualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.</p>
-
-<p>Este código de amostra pode detetar um GET do cliente. Note que isto irá bloquear até que os primeiros 3 bytes de uma mensagem estejam disponíveis. Deverão ser investigadas soluções alternativas para ambientes de produção.</p>
-
-<pre class="brush: cpp notranslate">using System.Text;
-using System.Text.RegularExpressions;
-
-while(client.Available &lt; 3)
-{
- // esperar para que hajam bytes suficientes disponiveis
-}
-
-Byte[] bytes = new Byte[client.Available];
-
-stream.Read(bytes, 0, bytes.Length);
-
-//traduzir bytes do pedido para uma string
-String data = Encoding.UTF8.GetString(bytes);
-
-if (Regex.IsMatch(data, "^GET")) {
-
-} else {
-
-}</pre>
-
-<p>A resposta é fácil de construir, mas pode ser um pouco difícil de compreender. A explicação completa do aperto de mão do servidor pode ser encontrada em <a href="https://tools.ietf.org/html/rfc6455#section-4.2.2">RFC 6455, secção 4.2.2</a>. Para os nossos propósitos, vamos apenas construir uma resposta simples.</p>
-
-<p>Deve:</p>
-
-<ol>
- <li>Obter o valor do cabeçalho de pedido da <code>Sec-WebSocket-Key</code> sem qualquer espaço em branco</li>
- <li>Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (um GUID especificado pela RFC 6455)</li>
- <li>Calcule o código SHA-1 e Base64 do mesmo</li>
- <li>Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.</li>
-</ol>
-
-<pre class="brush: cpp notranslate"><em>
-</em>if (new System.Text.RegularExpressions.Regex("^GET").IsMatch(data))
-{
-    const string eol = "\r\n"; // HTTP/1.1 define a sequencia "CR LF" como o marcador de fim de linha
-
-    Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
-        + "Connection: Upgrade" + eol
-        + "Upgrade: websocket" + eol
-        + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
-            System.Security.Cryptography.SHA1.Create().ComputeHash(
-                Encoding.UTF8.GetBytes(
-                    new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
-                )
-            )
-        ) + eol
-        + eol);
-
-    stream.Write(response, 0, response.Length);
-}
-</pre>
-
-<h2 id="Descodificar_mensagens">Descodificar mensagens</h2>
-
-<p>Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.</p>
-
-<p>Se enviarmos "MDN", recebemos estes bytes:</p>
-
-<table>
- <tbody>
- <tr>
- <td>129</td>
- <td>131</td>
- <td>61</td>
- <td>84</td>
- <td>35</td>
- <td>6</td>
- <td>112</td>
- <td>16</td>
- <td>109</td>
- </tr>
- </tbody>
-</table>
-
-<p>Vejamos o que significam estes bytes.</p>
-
-<p>O primeiro byte, que tem actualmente um valor de 129, é um bitfield que se decompõe da seguinte forma:</p>
-
-<table>
- <thead>
- <tr>
- <th scope="col">FIN (Bit 0)</th>
- <th scope="col">RSV1 (Bit 1)</th>
- <th scope="col">RSV2 (Bit 2)</th>
- <th scope="col">RSV3 (Bit 3)</th>
- <th scope="col">Opcode (Bit 4:7)</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>1</td>
- <td>0</td>
- <td>0</td>
- <td>0</td>
- <td>0x1=0001</td>
- </tr>
- </tbody>
-</table>
-
-<ul>
- <li>FIN bit: Este bit indica se a mensagem completa foi enviada pelo cliente. As mensagens podem ser enviadas em <em>frames</em>, mas por agora vamos manter as coisas simples.</li>
- <li>RSV1, RSV2, RSV3: Estes bits devem ser 0, a menos que seja negociada uma extensão que lhes forneça um valor não nulo.</li>
- <li><span style="line-height: 1.572;"><em>Opcode</em>: Estes bits descrevem o tipo de mensagem recebida. O código <em>Opcode </em>0x1 significa que se trata de uma mensagem de texto (ver <a href="http://tools.ietf.org/html/rfc6455#section-5.2">lista completa de <em>Opcodes</em></a>).</span></li>
-</ul>
-
-<p>O segundo byte, que tem atualmente um valor de 131, é outro campo de bits que se decompõe assim:</p>
-
-<table>
- <thead>
- <tr>
- <th scope="col">MASK (Bit 0)</th>
- <th scope="col">Comprimento do conteúdo da mensagem (Bit 1:7)</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>1</td>
- <td>0x83=0000011</td>
- </tr>
- </tbody>
-</table>
-
-<ul>
- <li>MASK bit: Define se os "dados de <em>payload</em>" são mascarados.  Se definida como 1, uma chave de máscara está presente em Masking-Key, e é utilizada para desmascarar os "dados de <em>payload</em>". Todas as mensagens do cliente para o servidor têm este bit definido.</li>
- <li>Comprimento do <em>payload</em>: Se este valor estiver entre 0 e 125, então é o comprimento da mensagem. Se for 126, os 2 bytes seguintes (inteiro de 16 bits sem assinatura) são o comprimento. Se for 127, os 8 bytes seguintes (inteiro de 64 bits sem assinatura) são o comprimento.</li>
-</ul>
-
-<div class="note">
-<p>Porque o primeiro bit é sempre 1 para mensagens cliente-servidor, pode subtrair 128 deste byte para se livrar do bit MASK.</p>
-</div>
-
-<p>Note que o bit MASK está definido na nossa mensagem. Isto significa que os quatro bytes seguintes (61, 84, 35, e 6) são os bytes de máscara utilizados para descodificar a mensagem. Estes bytes mudam com cada mensagem.</p>
-
-<p>Os restantes bytes são a <em>payload</em> da mensagem codificada.</p>
-
-<h3 id="Algoritmo_para_descodificar">Algoritmo para descodificar</h3>
-
-<p><em>D<sub>i</sub></em> = <em>E<sub>i</sub></em> XOR <em>M</em><sub>(<em>i</em> mod 4)</sub></p>
-
-<p>onde <em>D</em> é a série de bytes da mensagem descodificados, <em>E</em> é a série de bytes da mensagem codificados, <em>M</em> é a série de bytes da chave, e <em>i</em> é o índice do byte da mensagem a ser descodificado.</p>
-
-<p>Exemplo em C#:</p>
-
-<pre class="brush: cpp notranslate">Byte[] decoded = new Byte[3];
-Byte[] encoded = new Byte[3] {112, 16, 109};
-Byte[] mask = new Byte[4] {61, 84, 35, 6};
-
-for (int i = 0; i &lt; encoded.Length; i++) {
- decoded[i] = (Byte)(encoded[i] ^ mask[i % 4]);
-}</pre>
-
-<h2 id="Exemplo_completo">Exemplo completo</h2>
-
-<p>Aqui tem o código, que foi explorado, na sua totalidade; isto inclui o código do cliente e do servidor.</p>
-
-<h3 id="wsserver.cs">wsserver.cs</h3>
-
-<pre class="notranslate">//
-// csc wsserver.cs
-// wsserver.exe
-
-using System;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Text.RegularExpressions;
-
-class Server {
- public static void Main() {
- string ip = "127.0.0.1";
- int port = 80;
- var server = new TcpListener(IPAddress.Parse(ip), port);
-
- server.Start();
- Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection...", ip, port);
-
- TcpClient client = server.AcceptTcpClient();
- Console.WriteLine("A client connected.");
-
- NetworkStream stream = client.GetStream();
-
- // enter to an infinite cycle to be able to handle every change in stream
- while (true) {
- while (!stream.DataAvailable);
- while (client.Available &lt; 3); // match against "get"
-
- byte[] bytes = new byte[client.Available];
- stream.Read(bytes, 0, client.Available);
- string s = Encoding.UTF8.GetString(bytes);
-
- if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase)) {
- Console.WriteLine("=====Handshaking from client=====\n{0}", s);
-
- // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
- // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
- // 3. Compute SHA-1 and Base64 hash of the new value
- // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
- string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
- string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
- byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
- string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);
-
- // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
- byte[] response = Encoding.UTF8.GetBytes(
- "HTTP/1.1 101 Switching Protocols\r\n" +
- "Connection: Upgrade\r\n" +
- "Upgrade: websocket\r\n" +
- "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");
-
- stream.Write(response, 0, response.Length);
- } else {
- bool fin = (bytes[0] &amp; 0b10000000) != 0,
- mask = (bytes[1] &amp; 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
-
- int opcode = bytes[0] &amp; 0b00001111, // expecting 1 - text message
- msglen = bytes[1] - 128, // &amp; 0111 1111
- offset = 2;
-
- if (msglen == 126) {
- // was ToUInt16(bytes, offset) but the result is incorrect
- msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
- offset = 4;
- } else if (msglen == 127) {
- Console.WriteLine("TODO: msglen == 127, needs qword to store msglen");
- // i don't really know the byte order, please edit this
- // msglen = BitConverter.ToUInt64(new byte[] { bytes[5], bytes[4], bytes[3], bytes[2], bytes[9], bytes[8], bytes[7], bytes[6] }, 0);
- // offset = 10;
- }
-
- if (msglen == 0)
- Console.WriteLine("msglen == 0");
- else if (mask) {
- byte[] decoded = new byte[msglen];
- byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
- offset += 4;
-
- for (int i = 0; i &lt; msglen; ++i)
- decoded[i] = (byte)(bytes[offset + i] ^ masks[i % 4]);
-
- string text = Encoding.UTF8.GetString(decoded);
- Console.WriteLine("{0}", text);
- } else
- Console.WriteLine("mask bit not set");
-
- Console.WriteLine();
- }
- }
- }
-}</pre>
-
-<h3 id="client.html">client.html</h3>
-
-<pre class="brush: html notranslate">&lt;!doctype html&gt;
-&lt;style&gt;
- textarea { vertical-align: bottom; }
- #output { overflow: auto; }
- #output &gt; p { overflow-wrap: break-word; }
- #output span { color: blue; }
- #output span.error { color: red; }
-&lt;/style&gt;
-&lt;h2&gt;WebSocket Test&lt;/h2&gt;
-&lt;textarea cols=60 rows=6&gt;&lt;/textarea&gt;
-&lt;button&gt;send&lt;/button&gt;
-&lt;div id=output&gt;&lt;/div&gt;
-&lt;script&gt;
- // http://www.websocket.org/echo.html
-
- var button = document.querySelector("button"),
- output = document.querySelector("#output"),
- textarea = document.querySelector("textarea"),
- // wsUri = "ws://echo.websocket.org/",
- wsUri = "ws://127.0.0.1/",
- websocket = new WebSocket(wsUri);
-
- button.addEventListener("click", onClickButton);
-
- websocket.onopen = function (e) {
- writeToScreen("CONNECTED");
- doSend("WebSocket rocks");
- };
-
- websocket.onclose = function (e) {
- writeToScreen("DISCONNECTED");
- };
-
- websocket.onmessage = function (e) {
- writeToScreen("&lt;span&gt;RESPONSE: " + e.data + "&lt;/span&gt;");
- };
-
- websocket.onerror = function (e) {
- writeToScreen("&lt;span class=error&gt;ERROR:&lt;/span&gt; " + e.data);
- };
-
- function doSend(message) {
- writeToScreen("SENT: " + message);
- websocket.send(message);
- }
-
- function writeToScreen(message) {
- output.insertAdjacentHTML("afterbegin", "&lt;p&gt;" + message + "&lt;/p&gt;");
- }
-
- function onClickButton() {
- var text = textarea.value;
-
- text &amp;&amp; doSend(text);
- textarea.value = "";
- textarea.focus();
- }
-&lt;/script&gt;</pre>
-
-<h2 id="Ver_também">Ver também</h2>
-
-<ul>
- <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_servidores_de_WebSocket">Escrever servidores de WebSocket</a></li>
-</ul>
-
-<div id="cke_pastebin"><em> </em></div>
diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html
deleted file mode 100644
index 173a3066fe..0000000000
--- a/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html
+++ /dev/null
@@ -1,258 +0,0 @@
----
-title: Escrever servidores de WebSocket
-slug: Web/API/WebSockets_API/Writing_WebSocket_servers
-tags:
- - Guía
- - HTML5
- - Tutorial
- - WebSocket
- - WebSocket API
- - WebSockets
-translation_of: Web/API/WebSockets_API/Writing_WebSocket_servers
-original_slug: Web/API/WebSockets_API/Escrever_servidores_de_WebSocket
----
-<div>{{APIRef("Websockets API")}}</div>
-
-<p>Um servidor WebSocket não é nada mais que uma aplicação que escuta qualquer porta de um servidor TCP que possui um protocolo específico. A tarefa de criar um servidor personalizado é uma tarefa complexa para a maioria; no entanto, é simples implementar um servidor simples de WebSocket numa plataforma á sua escolha.</p>
-
-<p>Um servidor WebSocket pode ser escrito em qualquer linguagem de servidor que suporte <a href="https://en.wikipedia.org/wiki/Berkeley_sockets">Berkeley sockets</a>, como C(++), Python, PHP, ou <a href="/en-US/docs/Web/JavaScript/Server-Side_JavaScript">server-side JavaScript</a>. Este tutorial não se foca em nenhuma linguagem em específico, mas serve como guia para facilitar o desenvolver do seu próprio server.</p>
-
-<p>A WebSocket server can be written in any server-side programming language that is capable of <a href="https://en.wikipedia.org/wiki/Berkeley_sockets">Berkeley sockets</a>, such as C(++), Python, <a href="/en-US/docs/PHP">PHP</a>, or <a href="/en-US/docs/Web/JavaScript/Server-Side_JavaScript">server-side JavaScript</a>. This is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server.</p>
-
-<p>This article assumes you're already familiar with how {{Glossary("HTTP")}} works, and that you have a moderate level of programming experience. Depending on language support, knowledge of TCP sockets may be required. The scope of this guide is to present the minimum knowledge you need to write a WebSocket server.</p>
-
-<div class="note">
-<p><strong>Note:</strong> Read the latest official WebSockets specification, <a href="http://datatracker.ietf.org/doc/rfc6455/?include_text=1">RFC 6455</a>. Sections 1 and 4-7 are especially interesting to server implementors. Section 10 discusses security and you should definitely peruse it before exposing your server.</p>
-</div>
-
-<p>A WebSocket server is explained on a very low level here. WebSocket servers are often separate and specialized servers (for load-balancing or other practical reasons), so you will often use a <a href="https://en.wikipedia.org/wiki/Reverse_proxy">reverse proxy</a> (such as a regular HTTP server) to detect WebSocket handshakes, pre-process them, and send those clients to a real WebSocket server. This means that you don't have to bloat your server code with cookie and authentication handlers (for example).</p>
-
-<h2 id="The_WebSocket_handshake">The WebSocket handshake</h2>
-
-<p>First, the server must listen for incoming socket connections using a standard TCP socket. Depending on your platform, this may be handled for you automatically. For example, let's assume that your server is listening on <code>example.com</code>, port 8000, and your socket server responds to {{HTTPMethod("GET")}} requests at <code>example.com/chat</code>.</p>
-
-<div class="warning">
-<p><strong>Warning:</strong> The server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. Browsers generally require a secure connection for WebSockets, although they may offer an exception for local devices.</p>
-</div>
-
-<p>The handshake is the "Web" in WebSockets. It's the bridge from HTTP to WebSockets. In the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. The server must be careful to understand everything the client asks for, otherwise security issues can occur.</p>
-
-<div class="blockIndicator note">
-<p><strong>Tip:</strong> The request-uri (<code>/chat</code> here) has no defined meaning in the spec. So, many people  use it to let one server handle multiple WebSocket applications. For example, <code>example.com/chat</code> could invoke a multiuser chat app, while <code>/game</code> on the same server might invoke a multiplayer game.</p>
-</div>
-
-<h3 id="Client_handshake_request">Client handshake request</h3>
-
-<p>Even though you're building a server, a client still has to start the WebSocket handshake process by contacting the server and requesting a WebSocket connection. So, you must know how to interpret the client's request. The <strong>client</strong> will send a pretty standard HTTP request with headers that looks like this (the HTTP version <strong>must</strong> be 1.1 or greater, and the method <strong>must</strong> be <code>GET</code>):</p>
-
-<pre class="notranslate">GET /chat HTTP/1.1
-Host: example.com:8000
-<strong>Upgrade: websocket</strong>
-<strong>Connection: Upgrade</strong>
-Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
-Sec-WebSocket-Version: 13
-
-</pre>
-
-<p>The client can solicit extensions and/or subprotocols here; see <a href="#Miscellaneous">Miscellaneous</a> for details. Also, common headers like {{HTTPHeader("User-Agent")}}, {{HTTPHeader("Referer")}}, {{HTTPHeader("Cookie")}}, or authentication headers might be there as well. Do whatever you want with those; they don't directly pertain to the WebSocket. It's also safe to ignore them. In many common setups, a reverse proxy has already dealt with them.</p>
-
-<div class="blockIndicator note">
-<p><strong>Tip:</strong> All <strong>browsers</strong> send an <a href="https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Origin"><code>Origin</code> header</a>. You can use this header for security (checking for same origin, automatically allowing or denying, etc.) and send a <a href="https://developer.mozilla.org/en-US/docs/HTTP/Response_codes#403">403 Forbidden</a> if you don't like what you see. However, be warned that non-browser agents can send a faked <code>Origin</code>. Most applications reject requests without this header.</p>
-</div>
-
-<p>If any header is not understood or has an incorrect value, the server should send a {{HTTPStatus("400")}} ("Bad Request")} response and immediately close the socket. As usual, it may also give the reason why the handshake failed in the HTTP response body, but the message may never be displayed (browsers do not display it). If the server doesn't understand that version of WebSockets, it should send a {{HTTPHeader("Sec-WebSocket-Version")}} header back that contains the version(s) it does understand.  In the example above, it indicates version 13 of the WebSocket protocol.</p>
-
-<p>The most interesting header here is {{HTTPHeader("Sec-WebSocket-Key")}}. Let's look at that next.</p>
-
-<div class="note">
-<p><strong>Note:</strong> <a href="https://developer.mozilla.org/en-US/docs/HTTP/Response_codes">Regular HTTP status codes</a> can be used only before the handshake. After the handshake succeeds, you have to use a different set of codes (defined in section 7.4 of the spec).</p>
-</div>
-
-<h3 id="Server_handshake_response">Server handshake response</h3>
-
-<p>When the <strong>server</strong> receives the handshake request, it should send back a special response that indicates that the protocol will be changing from HTTP to WebSocket. That header looks something like the following (remember each header line ends with <code>\r\n</code> and put an extra <code>\r\n</code> after the last one to indicate the end of the header):</p>
-
-<pre class="notranslate"><strong>HTTP/1.1 101 Switching Protocols</strong>
-Upgrade: websocket
-Connection: Upgrade
-<strong>Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
-
-</strong></pre>
-
-<p>Additionally, the server can decide on extension/subprotocol requests here; see <a href="#Miscellaneous">Miscellaneous</a> for details. The <code>Sec-WebSocket-Accept</code> header is important in that the server must derive it from the {{HTTPHeader("Sec-WebSocket-Key")}} that the client sent to it. To get it, c<span style="line-height: 1.5em;">oncatenate the client's </span><code style="font-size: 14px;">Sec-WebSocket-Key</code><span style="line-height: 1.5em;"> and the string "</span><code style="font-size: 14px;">258EAFA5-E914-47DA-95CA-C5AB0DC85B11</code><span style="line-height: 1.5em;">" together (it's a "</span><a href="https://en.wikipedia.org/wiki/Magic_string" style="line-height: 1.5em;">magic string</a><span style="line-height: 1.5em;">"), </span><span style="line-height: 1.5em;">take the </span><a href="https://en.wikipedia.org/wiki/SHA-1" style="line-height: 1.5em;">SHA-1 hash</a><span style="line-height: 1.5em;"> of the result, and </span><span style="line-height: 1.5em;">return the </span><a href="https://en.wikipedia.org/wiki/Base64" style="line-height: 1.5em;">base64</a><span style="line-height: 1.5em;"> encoding of that hash.</span></p>
-
-<div class="note">
-<p><strong>Note:</strong> This seemingly overcomplicated process exists so that it's obvious to the client whether the server supports WebSockets. This is important because security issues might arise if the server accepts a WebSockets connection but interprets the data as a HTTP request.</p>
-</div>
-
-<p>So if the Key was "<code>dGhlIHNhbXBsZSBub25jZQ==</code>", the <code>Sec-WebSocket-Accept</code> header's value is "<code>s3pPLMBiTxaQ9kYGzzhZRbK+xOo=</code>". Once the server sends these headers, the handshake is complete and you can start swapping data!</p>
-
-<div class="note">
-<p><strong>Note:</strong> The server can send other headers like {{HTTPHeader("Set-Cookie")}}, or ask for authentication or redirects via other status codes, before sending the reply handshake.</p>
-</div>
-
-<h3 id="Keeping_track_of_clients">Keeping track of clients</h3>
-
-<p>This doesn't directly relate to the WebSocket protocol, but it's worth mentioning here: your server must keep track of clients' sockets so you don't keep handshaking again with clients who have already completed the handshake. The same client IP address can try to connect multiple times. However, the server can deny them if they attempt too many connections in order to save itself from <a href="https://en.wikipedia.org/wiki/Denial_of_service">Denial-of-Service attacks</a>.</p>
-
-<p>For example, you might keep a table of usernames or ID numbers along with the corresponding {{domxref("WebSocket")}} and other data that you need to associate with that connection.</p>
-
-<h2 id="Exchanging_data_frames">Exchanging data frames</h2>
-
-<p>Either the client or the server can choose to send a message at any time — that's the magic of WebSockets. However, extracting information from these so-called "frames" of data is a not-so-magical experience. Although all frames follow the same specific format, data going from the client to the server is masked using <a href="https://en.wikipedia.org/wiki/XOR_cipher">XOR encryption</a> (with a 32-bit key). Section 5 of the specification describes this in detail.</p>
-
-<h3 id="Format">Format</h3>
-
-<p>Each data frame (from the client to the server or vice-versa) follows this same format:</p>
-
-<pre class="notranslate">Frame format:
-​​
- 0 1 2 3
- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- +-+-+-+-+-------+-+-------------+-------------------------------+
- |F|R|R|R| opcode|M| Payload len | Extended payload length |
- |I|S|S|S| (4) |A| (7) | (16/64) |
- |N|V|V|V| |S| | (if payload len==126/127) |
- | |1|2|3| |K| | |
- +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
- | Extended payload length continued, if payload len == 127 |
- + - - - - - - - - - - - - - - - +-------------------------------+
- | |Masking-key, if MASK set to 1 |
- +-------------------------------+-------------------------------+
- | Masking-key (continued) | Payload Data |
- +-------------------------------- - - - - - - - - - - - - - - - +
- : Payload Data continued ... :
- + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
- | Payload Data continued ... |
- +---------------------------------------------------------------+</pre>
-
-<p>The MASK bit tells whether the message is encoded. Messages from the client must be masked, so your server must expect this to be 1. (In fact, <a href="http://tools.ietf.org/html/rfc6455#section-5.1">section 5.1 of the spec</a> says that your server must disconnect from a client if that client sends an unmasked message.) When sending a frame back to the client, do not mask it and do not set the mask bit. We'll explain masking later. <em>Note: You must mask messages even when using a secure socket. </em>RSV1-3 can be ignored, they are for extensions.</p>
-
-<p>The opcode field defines how to interpret the payload data: <span style="font-family: courier new,andale mono,monospace; line-height: 1.5;"><code>0x0</code> </span><span style="line-height: 1.5;">for continuation,</span><span style="font-family: courier new,andale mono,monospace; line-height: 1.5;"> </span><code style="font-style: normal; line-height: 1.5;">0x1</code><span style="line-height: 1.5;"> for text (which is always encoded in UTF-8), </span><code style="font-style: normal; line-height: 1.5;">0x2</code><span style="line-height: 1.5;"> for binary, and other so-called "control codes" that will be discussed later. In this version of WebSockets, <code>0x3</code> to <code>0x7</code> and <code>0xB</code> to <code>0xF</code> have no meaning.</span></p>
-
-<p>The FIN bit tells whether this is the last message in a series. If it's 0, then the server keeps listening for more parts of the message; otherwise, the server should consider the message delivered. More on this later.</p>
-
-<h3 id="Decoding_Payload_Length">Decoding Payload Length</h3>
-
-<p>To read the payload data, you must know when to stop reading. That's why the payload length is important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps:</p>
-
-<ol>
- <li>Read bits 9-15 (inclusive) and interpret that as an unsigned integer. If it's 125 or less, then that's the length; you're <strong>done</strong>. If it's 126, go to step 2. If it's 127, go to step 3.</li>
- <li>Read the next 16 bits and interpret those as an unsigned integer. You're <strong>done</strong>.</li>
- <li>Read the next 64 bits and interpret those as an unsigned integer. (The most significant bit <em>must</em> be 0.) You're <strong>done</strong>.</li>
-</ol>
-
-<h3 id="Reading_and_Unmasking_the_Data">Reading and Unmasking the Data</h3>
-
-<p>If the MASK bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); this is the masking key. <span style="line-height: 1.5;">Once the payload length and masking key is decoded, you can read that number of bytes from the socket. Let's call the data <strong>ENCODED</strong>, and the key <strong>MASK</strong>. To get <strong>DECODED</strong>, loop through the octets (bytes a.k.a. characters for text data) of <strong>ENCODED</strong> and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid JavaScript):</span></p>
-
-<pre class="notranslate">var DECODED = "";
-for (var i = 0; i &lt; ENCODED.length; i++) {
- DECODED[i] = ENCODED[i] ^ MASK[i % 4];
-<span style="line-height: 1.5;">}</span></pre>
-
-<p><span style="line-height: 1.5;">Now you can figure out what <strong>DECODED</strong> means depending on your application.</span></p>
-
-<h3 id="Message_Fragmentation">Message Fragmentation</h3>
-
-<p>The FIN and opcode fields work together to send a message split up into separate frames.  This is called message fragmentation. Fragmentation is only available on opcodes <code>0x0</code> to <code>0x2</code>.</p>
-
-<p><span style="line-height: 1.5;">Recall that the opcode tells what a frame is meant to do. If it's <code>0x1</code>, the payload is text. If it's <code>0x2</code>, the payload is binary data.</span><span style="line-height: 1.5;"> However, if it's </span><code style="font-style: normal; line-height: 1.5;">0x0,</code><span style="line-height: 1.5;"> the frame is a continuation frame; this means the server should concatenate the frame's payload to the last frame it received from that client.</span><span style="line-height: 1.5;"> Here is a rough sketch, in which a server reacts to a client sending text messages. The first message is sent in a single frame, while the second message is sent across three frames. FIN and opcode details are shown only for the client:</span></p>
-
-<pre style="font-size: 14px;"><strong>Client:</strong> FIN=1, opcode=0x1, msg="hello"
-<strong>Server:</strong> <em>(process complete message immediately) </em>Hi.
-<strong>Client:</strong> FIN=0, opcode=0x1, msg="and a"
-<strong>Server:</strong> <em>(listening, new message containing text started)</em>
-<strong>Client:</strong> FIN=0, opcode=0x0, msg="happy new"
-<strong>Server:</strong> <em>(listening, payload concatenated to previous message)</em>
-<strong>Client:</strong> FIN=1, opcode=0x0, msg="year!"
-<strong>Server:</strong> <em>(process complete message) </em>Happy new year to you too!</pre>
-
-<p>Notice the first frame contains an entire message (has <code>FIN=1</code> and <code>opcode!=0x0</code>), so the server can process or respond as it sees fit. The second frame sent by the client has a text payload (<code>opcode=0x1</code>), but the entire message has not arrived yet (<code>FIN=0</code>). All remaining parts of that message are sent with continuation frames (<code>opcode=0x0</code>), and the final frame of the message is marked by <code>FIN=1</code>. <a href="http://tools.ietf.org/html/rfc6455#section-5.4">Section 5.4 of the spec</a> describes message fragmentation.</p>
-
-<h2 id="Pings_and_Pongs_The_Heartbeat_of_WebSockets">Pings and Pongs: The Heartbeat of WebSockets</h2>
-
-<p>At any point after the handshake, either the client or the server can choose to send a ping to the other party. When the ping is received, the recipient must send back a pong as soon as possible. You can use this to make sure that the client is still connected, for example.</p>
-
-<p>A ping or pong is just a regular frame, but it's a <strong>control frame</strong>. Pings have an opcode of <code>0x9</code>, and pongs have an opcode of <code>0xA</code>. When you get a ping, send back a pong with the exact same Payload Data as the ping (for pings and pongs, the max payload length is 125). You might also get a pong without ever sending a ping; ignore this if it happens.</p>
-
-<div class="note">
-<p>If you have gotten more than one ping before you get the chance to send a pong, you only send one pong.</p>
-</div>
-
-<h2 id="Closing_the_connection">Closing the connection</h2>
-
-<p>To close a connection either the client or server can send a control frame with data containing a specified control sequence to begin the closing handshake (detailed in <a href="http://tools.ietf.org/html/rfc6455#section-5.5.1">Section 5.5.1</a>). Upon receiving such a frame, the other peer sends a Close frame in response. The first peer then closes the connection. Any further data received after closing of connection is then discarded. </p>
-
-<h2 id="Miscellaneous_2"><a name="Miscellaneous">Miscellaneous</a></h2>
-
-<div class="note">
-<p>WebSocket codes, extensions, subprotocols, etc. are registered at the <a href="http://www.iana.org/assignments/websocket/websocket.xml">IANA WebSocket Protocol Registry</a>.</p>
-</div>
-
-<p>WebSocket extensions and subprotocols are negotiated via headers during <a href="#Handshake">the handshake</a>. Sometimes extensions and subprotocols very similar, but there is a clear distinction. Extensions control the WebSocket <em>frame</em> and <em>modify</em> the payload, while subprotocols structure the WebSocket <em>payload</em> and <em>never modify</em> anything. Extensions are optional and generalized (like compression); subprotocols are mandatory and localized (like ones for chat and for MMORPG games).</p>
-
-<h3 id="Extensions">Extensions</h3>
-
-<div class="note">
-<p><strong>This section needs expansion. Please edit if you are equipped to do so.</strong></p>
-</div>
-
-<p>Think of an extension as compressing a file before e-mailing it to someone. Whatever you do, you're sending the <em>same</em> data in different forms. The recipient will eventually be able to get the same data as your local copy, but it is sent differently. That's what an extension does. WebSockets defines a protocol and a simple way to send data, but an extension such as compression could allow sending the same data but in a shorter format.</p>
-
-<div class="note">
-<p>Extensions are explained in sections 5.8, 9, 11.3.2, and 11.4 of the spec.</p>
-</div>
-
-<p><em>TODO</em></p>
-
-<h3 id="Subprotocols">Subprotocols</h3>
-
-<p>Think of a subprotocol as a custom <a href="https://en.wikipedia.org/wiki/XML_schema">XML schema</a> or <a href="https://en.wikipedia.org/wiki/Document_Type_Definition">doctype declaration</a>. You're still using XML and its syntax, but you're additionally restricted by a structure you agreed on. WebSocket subprotocols are just like that. They do not introduce anything fancy, they just establish structure. Like a doctype or schema, both parties must agree on the subprotocol; unlike a doctype or schema, the subprotocol is implemented on the server and cannot be externally refered to by the client.</p>
-
-<div class="note">
-<p>Subprotocols are explained in sections 1.9, 4.2, 11.3.4, and 11.5 of the spec.</p>
-</div>
-
-<p>A client has to ask for a specific subprotocol. To do so, it will send something like this <em>as part of the original handshake</em>:</p>
-
-<pre class="notranslate">GET /chat HTTP/1.1
-...
-Sec-WebSocket-Protocol: soap, wamp
-
-</pre>
-
-<p>or, equivalently:</p>
-
-<pre class="notranslate">...
-Sec-WebSocket-Protocol: soap
-Sec-WebSocket-Protocol: wamp
-
-</pre>
-
-<p>Now the server must pick one of the protocols that the client suggested and it supports. If there is more than one, send the first one the client sent. Imagine our server can use both <code>soap</code> and <code>wamp</code>. Then, in the response handshake, it sends:</p>
-
-<pre class="notranslate">Sec-WebSocket-Protocol: soap
-
-</pre>
-
-<div class="warning">
-<p>The server can't send more than one <code>Sec-Websocket-Protocol</code> header.<br>
- <span style="line-height: 1.5;">If the server doesn't want to use a</span><span style="line-height: 1.5;">ny subprotocol, </span><em><strong style="line-height: 1.5;">it shouldn't send any <code>Sec-WebSocket-Protocol</code> header</strong></em><span style="line-height: 1.5;">. Sending a blank header is incorrect. The client may close the connection if it doesn't get the subprotocol it wants.</span></p>
-</div>
-
-<p>If you want your server to obey certain subprotocols, then naturally you'll need extra code on the server. Let's imagine we're using a subprotocol <code>json</code>. In this subprotocol, all data is passed as <a href="https://en.wikipedia.org/wiki/JSON">JSON</a>. If the client solicits this protocol and the server wants to use it, the server needs to have a JSON parser. Practically speaking, this will be part of a library, but the server needs to pass the data around.</p>
-
-<div class="note">
-<p><strong>Tip:</strong> To avoid name conflict, it's recommended to make your subprotocol name part of a domain string. If you are building a custom chat app that uses a proprietary format exclusive to Example Inc., then you might use this: <code>Sec-WebSocket-Protocol: chat.example.com</code>. Note that this isn't required, it's just an optional convention, and you can use any string you wish.</p>
-</div>
-
-<h2 id="Related">Related</h2>
-
-<ul>
- <li><a href="https://github.com/alexhultman/libwshandshake">WebSocket handshake library in C++</a></li>
- <li><a href="/en-US/docs/WebSockets/Writing_WebSocket_client_applications">Writing WebSocket client applications</a></li>
- <li><a href="/en-US/docs/WebSockets/Writing_WebSocket_server" title="/en-US/docs/WebSockets/Writing_WebSocket_server">Tutorial: Websocket server in C#</a></li>
- <li><a href="/en-US/docs/WebSockets/WebSocket_Server_Vb.NET">Tutorial: Websocket server in VB.NET</a></li>
- <li><a href="/en-US/docs/Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java">Tutorial: Websocket server in Java</a></li>
-</ul>