TCP Socket

  • Revision slug: WebAPI/TCP_Socket
  • Revision title: TCP Socket
  • Revision id: 444209
  • Created:
  • Creator: kscarfone
  • Is current revision? No
  • Comment Editorial review

Revision Content

{{ non-standard_header() }}

{{ B2GOnlyHeader2('privileged') }}

Summary

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.

Overview

This API is available through the {{domxref("window.navigator.mozTCPSocket","navigator.mozTCPSocket")}} property which is itself a {{domxref("TCPSocket")}} object.

Opening a socket

Opening a socket is done with the {{domxref("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 {{event("data")}} event, with the expected values string or arraybuffer. By default, it is string.
var socket = navigator.mozTCPSocket.open('localhost', 80);

Note: Only certified apps can use a port below 1024.

Sending data

Sending data is done using the {{domxref("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 {{domxref("TCPSocket.send()","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 {{event("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 {{domxref("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();

Getting data

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).

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

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.

Closing a socket

Closing a socket is simply done using {{domxref("TCPSocket.close()")}}.

Standard

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.

See also

  • {{domxref("TCPSocket")}}

Revision Source

<p>{{ non-standard_header() }}</p>
<p>{{ B2GOnlyHeader2('privileged') }}</p>
<h2 id="Summary">Summary</h2>
<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="Overview">Overview</h2>
<p>This API is available through the {{domxref("window.navigator.mozTCPSocket","navigator.mozTCPSocket")}} property which is itself a {{domxref("TCPSocket")}} object.</p>
<h3 id="Opening_a_socket">Opening a 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>Note:</strong> Only certified apps can use a port below 1024.</p>
</div>
<h3 id="Sending_data">Sending data</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="Getting_data">Getting data</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="Closing_a_socket">Closing a socket</h3>
<p>Closing a socket is simply done using {{domxref("TCPSocket.close()")}}.</p>
<h2 id="Standard">Standard</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="See_also">See also</h2>
<ul>
  <li>{{domxref("TCPSocket")}}</li>
</ul>
Revert to this revision