aboutsummaryrefslogtreecommitdiff
path: root/files/pt-br/webapi/tcp_socket/index.html
blob: 48b49f41326eb963c5dda7ac5f1b6cc71e0ddab5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
---
title: TCP Socket
slug: WebAPI/TCP_Socket
translation_of: Archive/B2G_OS/API/TPC_Socket_API
---
<p>{{ non-standard_header() }}</p>
<p>{{ B2GOnlyHeader2('privileged') }}</p>
<h2 id="Sumário">Sumário</h2>
<p>A API TCPSocket oferece</p>
<p>The TCPSocket API offers a whole API to open and use a TCP connection. This allows app makers to implement any protocol available on top of TCP such as IMAP, IRC, POP, HTTP, etc., or even build their own to sustain any specific needs they could have.</p>
<h2 id="Permissões">Permissões</h2>
<p>Para utilizar essa API, como todas as API privilegiadas, é necessário que tenha permissão para utilizar dentro do <a href="/en-US/docs/Web/Apps/Manifest">app manifest</a>.</p>
<pre class="brush: json">"permissions" : {
  "tcp-socket" : {
    "description" : "Create TCP sockets and communicate over them."
  }
}</pre>
<h2 id="Overview">Overview</h2>
<p>A API está disponível através da propriedade {{domxref("window.navigator.mozTCPSocket","navigator.mozTCPSocket")}} que por si é um objeto {{domxref("TCPSocket")}}.</p>
<h3 id="Abrindo_um_socket.">Abrindo um socket.</h3>
<p>Opening a socket is done with the {{domxref("TCPSocket.open()")}} method. This method expects up to three parameters:</p>
<ol>
 <li>A string representing the hostname of the server to connect to (it can also be its raw IP address).</li>
 <li>A number representing the TCP port to be used by the socket (some protocols have a standard port, for example 80 for HTTP, 447 for SSL, 25 for SMTP, etc. Port numbers beyond 1024 are not assigned to any specific protocol and can be used for any purpose.)</li>
 <li>A optional object containing up to two options: a boolean named <code>useSSL</code> is the socket needed to use SSL, <code>false</code> by default; and a string named <code>binaryType</code> allows to state the type of data retrieved by the application through the {{event("data")}} event, with the expected values <code>string</code> or <code>arraybuffer</code>. By default, it is <code>string</code>.</li>
</ol>
<pre class="brush: js">var socket = navigator.mozTCPSocket.open('localhost', 80);</pre>
<div class="note">
 <p><strong>Nota:</strong> Apenas aplicações certificadas podem utilizar portas abaixo de 1024.</p>
</div>
<h3 id="Enviando_dado">Enviando dado</h3>
<p>Sending data is done using the {{domxref("TCPSocket.send()")}} method. The data sent can be either a string or a <code><a href="/en-US/docs/JavaScript/Typed_arrays/Uint8Array" title="/en-US/docs/JavaScript/Typed_arrays/Uint8Array">Uint8Array</a></code> object; however, remember that a TCP socket always deals with binary data. For that reason, it's a lot safer to use <code><a href="/en-US/docs/JavaScript/Typed_arrays/Uint8Array" title="/en-US/docs/JavaScript/Typed_arrays/Uint8Array">Uint8Array</a></code> instead of a string when sending data.</p>
<p>As per the TCP protocol, it's a good optimization to send a maximum of 64kb of data at the same time. As long as less than 64kb has been buffered, a call to the {{domxref("TCPSocket.send()","send")}} method returns <code>true</code>. Once the buffer is full, the method will return <code>false</code> which indicates the application should make a pause to flush the buffer. Each time the buffer is flushed, a {{event("drain")}} event is fired and the application can use it to resume data sending.</p>
<p>It's possible to know exactly the current amount of data buffered with the {{domxref("TCPSocket.bufferedAmount")}} property.</p>
<pre class="brush: js">function getData() {
  var data;

  // do stuff that will retrieve data

  return data;
}

function pushData() {
  var data;

  do {
    data = getData();
  } while (data != null &amp;&amp; socket.send(data));
}

// Each time the buffer is flushed
// we try to send data again.
socket.ondrain = pushData;

// Start sending data.
pushData();
</pre>
<h3 id="Pegando_dado">Pegando dado</h3>
<p>Each time the socket gets some data from the host, it fires a {{event("data")}} event. This event will give access to the data from the socket. The type of the data depends on the option set when the socket was opened (see above).</p>
<pre class="brush: js">socket.ondata = function (event) {
  if (typeof event.data === 'string') {
    console.log('Get a string: ' + event.data);
  } else {
    console.log('Get a Uint8Array');
  }
}</pre>
<p>As the {{event("data")}} event is fired as much as needed, it can sometimes be necessary to pause the flow of incoming data. To that end, calling the {{domxref("TCPSocket.suspend()")}} method will pause reading incoming data and stop firing the {{event("data")}}. It's possible to start reading data and firing events again by calling the {{domxref("TCPSocket.resume()")}} method.</p>
<h3 id="Fechando_um_socket">Fechando um socket</h3>
<p>Closing a socket is simply done using {{domxref("TCPSocket.close()")}}.</p>
<h2 id="Padrão">Padrão</h2>
<p>Not part of any specification yet; however, this API is discussed at W3C as part of the <a class="external" href="http://www.w3.org/2012/sysapps/" rel="external" title="http://www.w3.org/2012/sysapps/">System Applications Working Group</a> under the <a href="http://www.w3.org/2012/sysapps/raw-sockets/" title="http://www.w3.org/2012/sysapps/raw-sockets/">Raw Sockets</a> proposal.</p>
<h2 id="Veja_também">Veja também</h2>
<ul>
 <li>{{domxref("TCPSocket")}}</li>
</ul>