aboutsummaryrefslogtreecommitdiff
path: root/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html')
-rw-r--r--files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html258
1 files changed, 258 insertions, 0 deletions
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
new file mode 100644
index 0000000000..173a3066fe
--- /dev/null
+++ b/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html
@@ -0,0 +1,258 @@
+---
+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>