Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

TCP Socket

Esta tradução está incompleta. Ajude atraduzir este artigo.

Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

This API is available on Firefox OS for privileged or certified applications only.

Sumário

A API TCPSocket oferece

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.

Permissões

Para utilizar essa API, como todas as API privilegiadas, é necessário que tenha permissão para utilizar dentro do app manifest.

"permissions" : {
  "tcp-socket" : {
    "description" : "Create TCP sockets and communicate over them."
  }
}

Overview

A API está disponível através da propriedade navigator.mozTCPSocket que por si é um objeto TCPSocket.

Abrindo um socket.

Opening a socket is done with the TCPSocket.open() method. This method expects up to three parameters:

  1. A string representing the hostname of the server to connect to (it can also be its raw IP address).
  2. 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.)
  3. A optional object containing up to two options: a boolean named useSSL is the socket needed to use SSL, false by default; and a string named binaryType allows to state the type of data retrieved by the application through the data event, with the expected values string or arraybuffer. By default, it is string.
var socket = navigator.mozTCPSocket.open('localhost', 80);

Nota: Apenas aplicações certificadas podem utilizar portas abaixo de 1024.

Enviando dado

Sending data is done using the TCPSocket.send() method. The data sent can be either a string or a Uint8Array object; however, remember that a TCP socket always deals with binary data. For that reason, it's a lot safer to use Uint8Array instead of a string when sending data.

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 send method returns true. Once the buffer is full, the method will return false which indicates the application should make a pause to flush the buffer. Each time the buffer is flushed, a drain event is fired and the application can use it to resume data sending.

It's possible to know exactly the current amount of data buffered with the TCPSocket.bufferedAmount property.

function getData() {
  var data;

  // do stuff that will retrieve data

  return data;
}

function pushData() {
  var data;

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

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

// Start sending data.
pushData();

Pegando dado

Each time the socket gets some data from the host, it fires a 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).

socket.ondata = function (event) {
  if (typeof event.data === 'string') {
    console.log('Get a string: ' + event.data);
  } else {
    console.log('Get a Uint8Array');
  }
}

As the 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 TCPSocket.suspend() method will pause reading incoming data and stop firing the data. It's possible to start reading data and firing events again by calling the TCPSocket.resume() method.

Fechando um socket

Closing a socket is simply done using TCPSocket.close().

Padrão

Not part of any specification yet; however, this API is discussed at W3C as part of the System Applications Working Group under the Raw Sockets proposal.

Veja também

Etiquetas do documento e colaboradores

 Colaboradores desta página: teoli, Fabio.Magnoni
 Última atualização por: teoli,