W3C

Raw Socket API

W3C First Public Working Draft 14 May 2013

This version:
http://www.w3.org/TR/2013/WD-raw-sockets-20130514/
Latest published version:
http://www.w3.org/TR/raw-sockets/
Latest editor's draft:
http://www.w3.org/2012/sysapps/raw-sockets/
Editor:
Claes Nilsson, Sony Mobile

Abstract

This API provides interfaces to raw UDP sockets, TCP client sockets and TCP server sockets.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document defines a System Level API for network communication over UDP and TCP sockets.

This document was published by the System Applications Working Group as a First Public Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-sysapps@w3.org (subscribe, archives). All feedback is welcome.

Publication as a First Public Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

1. Introduction

This section is non-normative.

Use this API to send and receive data over the network using TCP or UDP.

2. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT, RECOMMENDED, MAY, and OPTIONAL in this specification are to be interpreted as described in [RFC2119].

This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.

Implementations that use ECMAScript to implement the APIs defined in this specification MUST implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL], as this specification uses that specification and terminology.

3. Terminology

The EventHandler interface represents a callback used for event handlers as defined in [HTML5].

The concepts queue a task and fire a simple event are defined in [HTML5].

The terms event handler and event handler event types are defined in [HTML5].

4. Security and privacy considerations

This API must be only exposed to trusted content.

5. Interface UDPSocket

The UDPSocket interface defines attributes and methods for UDP communication

Example 1
// 
// This example shows a simple implementation of UPnP-SSDP M-SEARCH discovery 
// using a multicast UDPSocket 
//

// Create a UDP socket
var mySocket = new UDPSocket (); 

// Build an SSDP M-SEARCH multicast message
var MSearch = "M-SEARCH * HTTP/1.1\r\n" +
"ST: " + ServiceType + "\r\n" +
"MAN: \"ssdp:discover\"\r\n" +
"HOST: 239.255.255.250:1900\r\n" +
"MX: 10\r\n\r\n";

var SSDPMulticastAddress = "239.255.255.250";
var SSDPMulticastPort = 1900;

// Join multicast group
mySocket.joinMulticastGroup (SSDPMulticastAddress);

try {
  // Send SSDP M-SEARCH multicast message
  var moreBufferingOK = mySocket.send(MSearch, SSDPMulticastAddress, 
                                      SSDPMulticastPort);
  console.log('M-SEARCH Sent!'); 
}        
catch(err) {  
  // Sending failed      
  console.error('Sending M-SEARCH failed: ' + err.name);
}       

// Receive M-SEARCH responses          
mysocket.onmessage = function (udpMessageEvent) { 
  // Convert received data from ArrayBuffer to string
  var data = arrayBufferToString (udpMessageEvent.data);    
  console.log("Remote address: " + udpMessageEvent.remoteAddress + 
              " Remote port: " + udpMessageEvent.remotePort +  
              " Received data" + data);
};       
Example 2
// 
// This example shows a a simple implementation of reception of UPnP-SSDP 
// NOTIFY multicast messages 
//

var SSDPMulticastAddress = "239.255.255.250";
var SSDPMulticastPort = 1900;           

// Create a UDP socket and bind it to the IP-address of the default 
// local interface and to the SSDP local port
var mySocket = new UDPSocket ({"localPort":SSDPMulticastPort});   

// Join multicast group
mySocket.joinMulticastGroup (SSDPMulticastAddress);         

// Receive SSDP NOTFIY         
mysocket.onmessage = function (UDPMessageEvent) { 
  // Convert received data from ArrayBuffer to string
  var data = arrayBufferToString (UDPMessageEvent.data);    
  console.log("Remote address: " + UDPMessageEvent.remoteAddress + 
              " Remote port: " + UDPMessageEvent.remotePort +  
              " Received data" + data);
};  
[Constructor (optional UDPOptions options)]
interface UDPSocket : EventTarget {
    readonly    attribute DOMString       localAddress;
    readonly    attribute unsigned short  localPort;
    readonly    attribute DOMString?      remoteAddress;
    readonly    attribute unsigned short? remotePort;
    readonly    attribute boolean         addressReuse;
    readonly    attribute boolean         loopback;
    readonly    attribute unsigned long   bufferedAmount;
    readonly    attribute ReadyState      readyState;;
                attribute EventHandler    ondrain;
                attribute EventHandler    onerror;
                attribute EventHandler    onmessage;
    void    close ();
    void    suspend ();
    void    resume ();
    void    joinMulticastGroup (DOMString multicastGroupAddress);
    void    leaveMulticastGroup (DOMString multicastGroupAddress);
    boolean send ((DOMString or Blob or ArrayBuffer or ArrayBufferView) data, optional DOMString? remoteAddress, optional unsigned short? remotePort);
};

5.1 Attributes

addressReuse of type boolean, readonly
true allows the socket to be bound to an address that is already in use. Can be set by the options argument in the constructor. Default is true.
bufferedAmount of type unsigned long, readonly
This attribute contains the number of bytes which have previously been buffered by calls to the send methods of this socket.
localAddress of type DOMString, readonly
The IPv4/6 address of the interface, e.g. wifi or 3G, that the UDPSocket object is bound to. Can be set by the options argument in the constructor. If not set the user agent binds the socket to the IPv4/6 address of the default local interface.
localPort of type unsigned short, readonly
The local port that the UDPSocket object is bound to. Can be set by the options argument in the constructor. If not set the user agent binds the socket to a random local port number.
loopback of type boolean, readonly
true means that data you send is looped back to your host. Can be set by the options argument in the constructor. Default is false.
ondrain of type EventHandler,
The ondrain event handler will be called upon detection that previously-buffered data has been written to the network and it is possible to buffer more data received from the application,
onerror of type EventHandler,
The onerror event handler will be called when there is an error. The data attribute of the event passed to the onerror handler will have a description of the kind of error.
onmessage of type EventHandler,
Event handler for received UDP data. The onmessage handler will be called repeatedly and asynchronously after the UDPSocket object has been created, every time a UDP datagram has been received and was read. At any time, the client may choose to pause reading and receiving onmessage callbacks, by calling the socket's suspend() method. Further invocations of onmessage will be paused until resume() is called.
readyState; of type ReadyState, readonly
The state of the UDP Socket object. A UDP Socket object can be in "open" or "closed" states.
remoteAddress of type DOMString, readonly , nullable
The default remote IPv4/6 address that is used for subsequent send() calls. Null if not stated by the options argument of the constructor.
remotePort of type unsigned short, readonly , nullable
The default remote port that is used for subsequent send() calls. Null if not stated by the options argument of the constructor

5.2 Methods

close

Closes the UDP socket. A closed UDP socket can not be used any more.

No parameters.
Return type: void
joinMulticastGroup

Joins a multicast group identified by the given address.

Note that even if the socket is only sending to a multicast address, it is a good practice to explicitely join the multicast group (otherwise some routers may not relay packets).

Parameter Type Nullable Optional Description
multicastGroupAddress DOMString The multicast group address.
Return type: void
leaveMulticastGroup

Leaves a multicast group membership identified by the given address.

Parameter Type Nullable Optional Description
multicastGroupAddress DOMString The multicast group address.
Return type: void
resume

Resume reading incoming UDP data and invoking onmessage as usual.

No parameters.
Return type: void
send

Sends data on the given UDP socket to the given address and port.

If remoteAddress and remotePort arguments are not given or null the destination is the default address and port given by the UDPSocket constructor's options argument's remoteAddress and remotePort fields.

Parameter Type Nullable Optional Description
data (DOMString or Blob or ArrayBuffer or ArrayBufferView) The data to write in one of the alternative representations as stated below:
  • Represented as a sequence of Unicode characters. [UNICODE].
  • As raw data represented by the Blob object. [FILE-API]
  • Represented as an ArrayBuffer object. [TYPED-ARRAYS]
  • Represented by the section of the buffer described by the ArrayBuffer object that the ArrayBufferView object references. [TYPED-ARRAYS].
remoteAddress DOMString The address of the remote machine.
remotePort unsigned short The port of the remote machine.
Return type: boolean
suspend

Pause reading incoming UDP data and invocations of the onmessage handler until resume is called.

No parameters.
Return type: void

When the UDPSocket constructor is invoked, the User Agent MUST run the following steps:

  1. If the options.localAddress argument is absent then bind the socket to the IPv4/6 address of the default local interface. Otherwise, if the requested local address is free or if it is in use and the options.addressReuse attribute is true or absent then bind the socket to the IPv4/6 address of the requested local interface. Else, throw an InvalidAccessError exception and abort these steps.
  2. If the options.localPort argument is absent bind then the socket to any available local port. Otherwise, if the requested local port is free or if it is in use and the options.addressReuse attribute is true or absent then bind the socket to the requested local port. Else, throw an InvalidAccessError exception and abort these steps.
  3. If the options.remoteAddress field is present then set the default remote address attribute of the socket to the requested address.
  4. If the options.remotePort field is present then set the default remote port attribute to the requested port.
  5. Create a new UDPSocket object and if the constructor's options argument is present set the corresponding attributes to the values of the fields that are present in the options argument, else set the corresponding attributes to the default values.
  6. Set the readyState attribute to "open".
  7. Set the bufferedAmount attribute to 0.
  8. Return the newly created UDPSocket object to the application.

The send method when invoked MUST run the following steps:

  1. If readyState is "closed" throw DOMException InvalidStateError and abort these steps.
  2. If the type of the data is not compatible any expected type, DOMString, Blob, ArraYBuffer or ArrayBufferView, then throw DOMException InvalidAccessError and abort these steps.
  3. If no default remote address and port was specified in the UDPSocket's constructor options.remoteAddress and options.remotePort arguments and the send method arguments remoteAddress and remotePort are not present or null then throw DOMException InvalidAccessError and abort these steps.
  4. If the data cannot be sent, e.g. because it would need to be buffered but the buffer is full or because the data is too long to pass atomically through the underlying protocol, the user agent MUST:
    1. Create a new instance of ErrorEvent.
    2. Set the error.name attribute of the ErrorEvent object to "NetworkError".
    3. queue a task to fire an event named error with the newly created ErrorEvent instance at the UDPSocket object.
    4. Close the UDP socket and set the readyState attribute to "closed".
    5. Abort these steps.
  5. Make a request to the system to send UDP data with data passed in the data parameter. If the send method arguments remoteAddress and remotePort are present use these as destination, else use the default address and port of the recipient as stated by the UDPSocket object constructor's options.remoteAddress and options.remotePort fields.
  6. When the request has been completed set the return value of the method to true or false as a hint to the caller that they may either continue sending more data immediately, or should want to wait until the transport layer has transmitted buffered data that already have been written to the socket before buffering more. When less than an implementation specific value has been buffered and it's safe to immediately write more set the return value to true. When more than an implementation specific value has been buffered set the return value to false. This means that the caller should wait before buffering more data by more calls to send until the ondrain event handler has been called.
  7. Any invocation of this method that does not throw an exception must increase the bufferedAmount attribute.
    • If the send data argument is DOMString the bufferedAmount attribute is increased by the number of bytes needed to express the argument as UTF-8. [UNICODE] [UTF-8]
    • If the send data argument is Blob the bufferedAmount attribute is increased by the size of the Blob object's raw data, in bytes. [FILE-API]
    • If the send data argument is ArrayBuffer the bufferedAmount attribute is increased by the length of the ArrayBuffer in bytes. [TYPED-ARRAYS]
    • If the send data argument is ArrayBufferView the bufferedAmount attribute is increased by the length of the ArrayBufferView in bytes. [TYPED-ARRAYS]

The close method when invoked MUST run the following steps:

  1. Close the socket, meaning that it can not be used to send and receive data any more, and set the readyState attribute to "closed".

Upon a new UDP datagram being received, the user agent MUST run the following steps:

  1. If it is not possible to convert the received UDP data to ArrayBuffer, [TYPED-ARRAYS], then:
    1. Create a new instance of ErrorEvent.
    2. Set the error.name attribute of the ErrorEvent object to "NetworkError".
    3. queue a task to fire an event named error with the newly created ErrorEvent instance at the UDPSocket object.
    4. Abort these steps.
  2. Create a new instance of UDPMessageEvent.
  3. Initialize the UDPMessageEvent object's data attribute to a new read-only ArrayBuffer object whose contents are the received UDP data [TYPED-ARRAYS].
  4. Set the remoteAddress attribute of the UDPMessageEvent object to the source address of the received UDP datagram.
  5. Set the remotePort attribute of the UDPMessageEvent object to the source port of the received UDP datagram.
  6. queue a task to fire an event named message with the newly created UDPMessageEvent instance at the UDPSocket object.

In the process of sending UDP data, upon a detection that previously-buffered data has been written to the network and it is possible to buffer more data received from the application, the user agent MUST:

  1. queue a task to fire an event named drain at the UDPSocket object.

5.3 Event handlers

The following are the event handlers (and their corresponding event handler event types) that MUST be supported as attributes by the UDPSocket object.

event handler event name
onmessage message
ondrain drain
onerror error

The message event SHALL implement the UDPMessageEvent interface.

The error event SHALL implement the ErrorEvent interface.

6. Interface TCPSocket

The TCPSocket interface defines attributes and methods for TCP communication

Example 3
// 
 // This example shows a simple TCP echo client. 
 // The client will send "Hello World" to the server on port 6789 and log 
 // what has been received from the server.
 //        
 try {
 
   //  Create a new TCP client socket and connect to remote host
   var mySocket = new TCPSocket ("127.0.0.1", 6789);  
   mySocket.onopen = function() {                    
     try {
       // Send data to server
       var moreBufferingOK = mySocket.send("Hello World");
       console.log('Data sent to server!'); 
       
       // Receive response from server
       mySocket.onmessage = function (messageEvent) {
         // Convert received data from ArrayBuffer to string
         var data = arrayBufferToString (messageEvent.data);  
         console.log('Data received from server: ' + data);
         
         // Close the connection
         mySocket.close();                               
       }
       
     }        
     catch(err) {  
       // Sending failed      
       console.error('Sending failed: ' + err.name);
     }                     
   }  
   
   // Connection has been closed 
   mySocket.onclose = function {
     console.log('Connection has been closed');
   }  
   
   // Handle errors
   mySocket.onerror = function(err) {
     console.error('Error: ' + err.name);
   }             
   
 }        
   catch(err) {  
   
   // Handle runtime exception    
   console.error('Could not create a TCP socket: ' + err.name);
 }     
[Constructor (DOMString remoteAddress, unsigned short remotePort, 
                 optional TCPOptions options)]
interface TCPSocket : EventTarget {
    readonly    attribute DOMString      remoteAddress;
    readonly    attribute DOMString      remotePort;
    readonly    attribute DOMString      localAddress;
    readonly    attribute unsigned short localPort;
    readonly    attribute unsigned long  bufferedAmount;
    readonly    attribute ReadyState     readyState;;
                attribute EventHandler   ondrain;
                attribute EventHandler   onopen;
                attribute EventHandler   onclose;
                attribute EventHandler   onhalfclose;
                attribute EventHandler   onerror;
                attribute EventHandler   onmessage;
    void    close ();
    void    halfclose ();
    void    suspend ();
    void    resume ();
    boolean send ((DOMString or Blob or ArrayBuffer or ArrayBufferView) data);
};

6.1 Attributes

bufferedAmount of type unsigned long, readonly
This attribute contains the number of bytes which have previously been buffered by calls to the send methods of this socket.
localAddress of type DOMString, readonly
The IPv4/6 address of the interface, e.g. wifi or 3G, that the TCPSocket object is bound to. Can be set by the options argument in the constructor. If not set the user agent binds the socket to the IPv4/6 address of the default local interface.
localPort of type unsigned short, readonly
The local port that the TCPSocket object is bound to. Can be set by the options argument in the constructor. If not set the user agent binds the socket to a random local port number.
onclose of type EventHandler,
The onclose event handler is called when the connection to the server has been closed, either cleanly by the server, or cleanly by the client calling close(), or if the connection was lost. If the connection was lost, onerror will be called prior to onclose.
ondrain of type EventHandler,
The ondrain event handler will be called upon detection that previously-buffered data has been written to the network and it is possible to buffer more data received from the application,
onerror of type EventHandler,
The onerror handler will be called when there is an error. The data attribute of the event passed to the onerror handler will have a description of the kind of error. If onerror is called before onopen, the error was connection refused, and onclose will not be called. If onerror is called after onopen, the connection was lost, and onclose will be called after onerror.
onhalfclose of type EventHandler,
The onhalfclose event handler is called when the remote peer has half closed the connection. This means that the remote peer can receive TCP messages but not send.
onmessage of type EventHandler,
Event handler for received TCP data. The onmessage handler will be called repeatedly and asynchronously after the TCPSocket object has been created, every time TCP data has been received and was read. At any time, the client may choose to pause reading and receiving onmessage callbacks, by calling the socket's suspend() method. Further invocations of onmessage will be paused until resume() is called.
onopen of type EventHandler,
The onopen event handler is called when the connection to the server has been established. If the connection is refused, onerror will be called, instead.
readyState; of type ReadyState, readonly
The state of the TCP Socket object.
remoteAddress of type DOMString, readonly
The IPv4/6 address of the peer as stated by the remoteAddress argument in the constructor.
remotePort of type DOMString, readonly
The port of the peer as stated by the remotePort argument in the constructor.

6.2 Methods

close

Closes the TCP socket.

No parameters.
Return type: void
halfclose

"Halfcloses" the TCP socket. This means that FIN is sent and that the socket no longer can be used to send data. However, receiving is still possible.

No parameters.
Return type: void
resume

Resume reading incoming TCP data and invoking onmessage as usual.

No parameters.
Return type: void
send

Sends data on the given connected TCP socket.

Parameter Type Nullable Optional Description
data (DOMString or Blob or ArrayBuffer or ArrayBufferView) The data to write in one of the alternative representations as stated below:
  • Represented as a sequence of Unicode characters. [UNICODE].
  • As raw data represented by the Blob object. [FILE-API]
  • Represented as an ArrayBuffer object. [TYPED-ARRAYS]
  • Represented by the section of the buffer described by the ArrayBuffer object that the ArrayBufferView object references. [TYPED-ARRAYS].
Return type: boolean
suspend

Pause reading incoming TCP data and invocations of the onmessage handler until resume is called.

No parameters.
Return type: void

When the TCPSocket constructor is invoked, the User Agent MUST run the following steps:

  1. If the remoteAddress argument is not a valid IPv4/6 address or the remotePort argument is not a valid port number then throw an InvalidAccessError exception and abort these steps, else set the remoteAddress and remotePort attributes to the requested values.
  2. If the options.localAddress argument is absent bind the socket to the IPv4/6 address of the default local interface. Otherwise, if the requested local address is free then bind the socket to the IPv4/6 address of the requested local interface. Else, throw an InvalidAccessError exception and abort these steps.
  3. If the options.localPort argument is absent bind then the socket to any available local port. Otherwise, if the requested local port is free bind the socket to the requested local port. Else, throw an InvalidAccessError exception and abort these steps.
  4. Set the localAddress and localPort attributes to the selected values according to above.
  5. Set the readyState attribute to "connecting".
  6. Set the bufferedAmount attribute to 0.
  7. Attempt to connect to the requested address and port in the background (without blocking scripts).
  8. Return the newly created TCPSocket object to the application.

The send method when invoked MUST run the following steps:

  1. If readyState is not "open" throw DOMException InvalidStateError and abort these steps.
  2. If the type of the data is not compatible any expected type, DOMString, Blob, ArraYBuffer or ArrayBufferView, then throw DOMException InvalidAccessError and abort these steps.
  3. If the data cannot be sent, e.g. because it would need to be buffered but the buffer is full or because the data is too long to pass atomically through the underlying protocol, the user agent MUST:
    1. Change the readyState attribute's value to "closed".
    2. Create a new instance of ErrorEvent.
    3. Set the error.name attribute of the ErrorEvent object to "NetworkError".
    4. queue a task to fire an event named error with the newly created ErrorEvent instance at the TCPSocket object.
    5. queue a task to fire an event named close at the TCPSocket object.
    6. Abort these steps.
  4. Make a request to the system to send TCP data with data passed in the data parameter to the address and port of the recipient as stated by the TCPSocket object constructor's remoteAddress and remotePort fields.
  5. When the requests has been completed set the return value of the method to true or false as a hint to the caller that they may either continue sending more data immediately, or should want to wait until the transport layer has transmitted buffered data that already have been written to the socket before buffering more. When less than an implementation specific value has been buffered and it's safe to immediately write more set the return value to true. When more than an implementation specific value has been buffered set the return value to false. This means that the caller should wait before buffering more data by more calls to send until the ondrain event handler has been called.
  6. Any invocation of this method that does not throw an exception must increase the bufferedAmount attribute.
    • If the send data argument is DOMString the bufferedAmount attribute is increased by the number of bytes needed to express the argument as UTF-8. [UNICODE] [UTF-8]
    • If the send data argument is Blob the bufferedAmount attribute is increased by the size of the Blob object's raw data, in bytes. [FILE-API]
    • If the send data argument is ArrayBuffer the bufferedAmount attribute is increased by the length of the ArrayBuffer in bytes. [TYPED-ARRAYS]
    • If the send data argument is ArrayBufferView the bufferedAmount attribute is increased by the length of the ArrayBufferView in bytes. [TYPED-ARRAYS]

The close method when invoked MUST run the following steps:

  1. If readyState is "closing" or "closed" then do nothing.
  2. If readyState is "connecting" then fail the connection attempt and set the readyState attribute to "closing".
  3. If readyState is "open" close the connection and set the readyState attribute to "closing".

The halfclose method when invoked MUST run the following steps:

  1. If readyState is "closing" or "closed" then do nothing.
  2. If readyState is "connecting" then complete the connection attempt. If succesful send FIN and set the readyState attribute to "halfclosed".
  3. If readyState is "open" then send FIN and set the readyState attribute to "halfclosed".

When a new TCP connection has been successfully established the user agent MUST run the following steps:

  1. Change the readyState attribute's value to "open".
  2. queue a task to fire an event named open at the TCPSocket object.

When the attempt to establish a new TCP connection (readyState is "connecting") has failed the user agent MUST run the following steps:

  1. Change the readyState attribute's value to "closed".
  2. Create a new instance of ErrorEvent.
  3. Set the error.name attribute of the ErrorEvent object to "NetworkError".
  4. queue a task to fire an event named error with the newly created ErrorEvent instance at the TCPSocket object.

When an established TCP connection (readyState is "open") is lost the user agent MUST run the following steps:

  1. Change the readyState attribute's value to "closed".
  2. Create a new instance of ErrorEvent.
  3. Set the error.name attribute of the ErrorEvent object to "NetworkError".
  4. queue a task to fire an event named error with the newly created ErrorEvent instance at the TCPSocket object.
  5. queue a task to fire an event named close at the TCPSocket object.

Upon a new TCP message being received, the user agent MUST run the following steps:

  1. If it is not possible to convert the received TCP data to ArrayBuffer, [TYPED-ARRAYS], then:
    1. Create a new instance of ErrorEvent.
    2. Set the error.name attribute of the ErrorEvent object to "NetworkError".
    3. queue a task to fire an event named error with the newly created ErrorEvent instance at the UDPSocket object.
    4. Abort these steps.
  2. Create a new instance of MessageEvent, [POSTMSG].
  3. Initialize the MessageEvent object's data attribute to a new read-only ArrayBuffer object whose contents are the received TCP data [TYPED-ARRAYS].
  4. queue a task to fire an event named message with the newly created MessageEvent instance at the TCPSocket object.

Note: It is up to the implementation the define how often the message event will be issued and how much data that will be delivered to the application with each MessageEvent instance.

In the process of sending TCP data, upon a detection that previously-buffered data has been written to the network and it is possible to buffer more data received from the application, the user agent MUST:

  1. queue a task to fire an event named drain at the TCPSocket object.

When a TCP connection has been closed cleanly, either by the server, or by the client calling close() the user agent MUST run the following steps:

  1. Set the readyState attribute's value to "closed".
  2. queue a task to fire an event named close at the TCPSocket object.

6.3 Event handlers

The following are the event handlers (and their corresponding event handler event types) that MUST be supported as attributes by the TCPSocket object.

event handler event name
onmessage message
ondrain drain
onopen open
onclose close
onhalfclose halfclose
onerror error

The message event SHALL implement the MessageEvent interface, [POSTMSG]. The event's data attribute is intialized to a new read-only ArrayBuffer object whose contents are the recieved UDP data. [TYPED-ARRAYS]

The error event SHALL implement the ErrorEvent interface.

7. Interface TCPServerSocket

The TCPServerSocket interface supports TCP server sockets that listens to connection attempts from TCP clients

Example 4
// 
// This example shows a simple TCP echo server. 
// The server will listen on port 6789 and respond back with what ever 
// has been sent to the server.
//        
try {
  //  Create a new server socket that listens on port 6789
  var myServerSocket = new TCPServerSocket ({"localPort":6789});
  
  myServerSocket.onconnect = function (connectEvent) { 
    var connectedSocket = connectEvent.connectedSocket;
    // Read the data
    connectedSocket.onmessage = function (messageEvent) {
       var data = messageEvent.data;               
       try {
         // Send data back to client
         var moreBufferingOK = connectedSocket.send(data);
         console.log('Response sent to client!'); 
       }        
         catch(err) {  
         // Sending failed      
         console.error('Sending failed: ' + err.name);
       }                                                            
    }  
    
    // Connection has been closed 
    connectedSocket.onclose = function {
      console.log('Connection has been closed');
    }        
  
  }
}        
catch(err) {  
  // Handle runtime exception    
  console.error('Could not create a TCP server socket: ' + err.name);
}      
[Constructor (optional TCPServerOptions options)]
interface TCPServerSocket : EventTarget {
    readonly    attribute DOMString      localAddress;
    readonly    attribute unsigned short localPort;
    readonly    attribute ReadyState     readyState;;
                attribute EventHandler   onconnect;
                attribute EventHandler   onerror;
    void close ();
    void suspend ();
    void resume ();
};

7.1 Attributes

localAddress of type DOMString, readonly
The IPv4/6 address of the interface, e.g. wifi or 3G, that the TCPServer Socket object is bound to. Can be set by the options argument in the constructor. If not set the user agent binds the socket to the IPv4/6 address of the default local interface.
localPort of type unsigned short, readonly
The local port that the TCPServerSocket object is bound to. Can be set by the options argument in the constructor. If not set the user agent binds the socket to a random local port number.
onconnect of type EventHandler,
Event handler for an accepted incoming connections on the specified port and address.
onerror of type EventHandler,
Event handler for errors on incoming connections. The data attribute of the event passed to the onerror handler will have a description of the kind of error.
readyState; of type ReadyState, readonly
The state of the TCP server object. A TCP server socket object can be in "open" or "closed" states.

7.2 Methods

close

Closes the TCP server socket, i.e. listening for incoming connections is stopped. Existing TCP connections are kept open.

No parameters.
Return type: void
resume

Resume listening for incoming connections and invocations of the onconnecion handler as usual.

No parameters.
Return type: void
suspend

Pause listening for incoming connections and invocations of the onconnecion handler until resume() is called.

No parameters.
Return type: void

When the TCPServerSocket constructor is invoked, the User Agent MUST run the following steps:

  1. If any input argument is invalid throw an InvalidAccessError exception and abort these steps.
  2. If the options.localAddress argument is absent then listen to the IPv4/6 address of the default local interface. Otherwise, if the requested local address is free then listen to the IPv4/6 address of the requested local interface. Else, throw an InvalidAccessError exception and abort these steps.
  3. If the options.localPort argument is absent then bind the socket to any available local port. Otherwise, if the requested local port is free then bind the socket to the requested local port. Else, throw an InvalidAccessError exception and abort these steps.
  4. Create a new TCPServerSocket object and set the localAddress and localPort attributes to selected values accoring to above.
  5. Set the readyState attribute to "open".
  6. Start listening for for connections on the specified port and address.
  7. Return the newly created TCPServerSocket object to the application.

The close method when invoked MUST run the following steps:

  1. If a TCP connection setup is in progress the connection setup is finalized according to the descriptions below.
  2. Stop listening to further connection attempts from clients.
  3. Set the readyState attribute to "closed".

Upon a new successful connection to the TCP server socket the user agent MUST run the following steps:

  1. Create a new instance of ConnectEvent.
  2. Let socket be a new instance of TCPSocket.
  3. set the remoteAddress attribute of socket to the IPv4/6 address of the peer.
  4. set the remotePort attribute of socket to the source port of the of the peer.
  5. set the localAddress attribute of socket to the used local IPv4/6 address.
  6. set the localPort attribute of socket to the used local source port.
  7. set the readyState attribute of socket to "open".
  8. set the bufferedAmount attribute of socket to 0.
  9. set the connectedSocket attribute of the ConnectEvent object to socket.
  10. queue a task to fire an event named connect with the newly created ConnectEvent instance at the TCPServerSocket object.

Upon a new connection attempt to the TCP server socket that can not be served, e.g. due to max number of open connections, the user agent MUST run the following steps:

  1. Create a new instance of ErrorEvent.
  2. Set the error.name attribute of the ErrorEvent object to "NetworkError".
  3. queue a task to fire an event named error with the newly created ErrorEvent instance at the TCPServerSocket object.

7.3 Event handlers

The following are the event handlers (and their corresponding event handler event types) that MUST be supported as attributes by the TCPServerSocket object.

event handler event name
onconnect connect
onerror error

The connect event SHALL implement the ConnectEvent interface.

The error event SHALL implement the ErrorEvent interface.

8. Interface UDPMessageEvent

The UDPMessageEvent interface represents events related to received UDP data. This interface extends the MessageEvent interface, [POSTMSG]

The event's data attribute is intialized to a new read-only ArrayBuffer object whose contents are the recieved UDP data, [TYPED-ARRAYS]

[NoInterfaceObject]
interface UDPMessageEvent : MessageEvent {
    readonly    attribute DOMString      remoteAddress;
    readonly    attribute unsigned short remotePort;
};

8.1 Attributes

remoteAddress of type DOMString, readonly
The address of the remote machine.
remotePort of type unsigned short, readonly
The port of the remote machine.

9. Interface ConnectEvent

The ConnectEvent interface represents events related to accepted connections to a TCP server socket.

[NoInterfaceObject]
interface ConnectEvent : Event {
    readonly    attribute TCPSocket connectedSocket;
};

9.1 Attributes

connectedSocket of type TCPSocket, readonly
The new TCP socket object for the accepted socket. This new socket object is to be used for further communication with the client.

10. Interface ErrorEvent

The ErrorEvent interface represents events related to TCP connection errors.

[NoInterfaceObject]
interface ErrorEvent : Event {
    readonly    attribute DOMError error;
};

10.1 Attributes

error of type DOMError, readonly
The detected error.

11. Dictionary UDPOptions

States the options for the UDPSocket. An instance of this dictionary can optionally be used in the constructor of the UDPSocket object, where all fields are optional.

dictionary UDPOptions {
    DOMString      localAddress;
    unsigned short localPort;
    DOMString      remoteAddress;
    unsigned short remotePort;
    boolean        addressReuse;
    boolean        loopback;
};

11.1 Dictionary UDPOptions Members

addressReuse of type boolean
true allows the socket to be bound to an address that is already in use. Default is true.
localAddress of type DOMString
The IPv4/6 address of the interface, e.g. wifi or 3G, that the UDPSocket object is bound to. If the field is omitted the user agent binds the socket to the IPv4/6 address of the default local interface.
localPort of type unsigned short
The local port that the UDPSocket object is bound to. If the the field is omitted the user agent binds the socket to a random local port number.
loopback of type boolean
true means that data you send is looped back to your host. Default is false.
remoteAddress of type DOMString
When present the default remote IPv4/6 address that is used for subsequent send() calls.
remotePort of type unsigned short
When present the default remote port that is used for subsequent send() calls.
Issue 1

Do we need secure transport for UDP sockets??

12. Dictionary TCPOptions

States the options for the TCPSocket. An instance of this dictionary can optionally be used in the constructor of the TCPSocket object, where all fields are optional.

dictionary TCPOptions {
    DOMString      localAddress;
    unsigned short localPort;
    boolean        useSecureTransport;
};

12.1 Dictionary TCPOptions Members

localAddress of type DOMString
The IPv4/6 address of the interface, e.g. wifi or 3G, that the UDPSocket object is bound to. If the field is omitted the user agent binds the socket to the IPv4/6 address of the default local interface.
localPort of type unsigned short
The local port that the UDPSocket object is bound to. If the the field is omitted the user agent binds the socket to a random local port number.
useSecureTransport of type boolean
true if socket uses SSL or TLS. Default is false.
Issue 2

Not sure if applications need to be able to bind the TCP Socket to local address/port?

Issue 3

Use of secure transport needs more investigation

13. Dictionary TCPServerOptions

States the options for the TCPServerSocket. An instance of this dictionary can optionally be used in the constructor of the TCPServerSocket object, where all fields are optional.

dictionary TCPServerOptions {
    DOMString      localAddress;
    unsigned short localPort;
    boolean        useSecureTransport;
};

13.1 Dictionary TCPServerOptions Members

localAddress of type DOMString
The IPv4/6 address of the interface, e.g. wifi or 3G, that the TCPServerSocket object is bound to. If the field is omitted the user agent binds the server socket to the IPv4/6 address of the default local interface.
localPort of type unsigned short
The local port that the TCPServerSocket object is bound to. If the the field is omitted the user agent binds the socket to an random local port number.
useSecureTransport of type boolean
true if socket uses SSL or TLS. Default is false.
Issue 4

Use of secure transport needs more investigation

14. Enums

14.1 ReadyState

enum ReadyState {
    "connecting",
    "open",
    "closing",
    "closed",
    "halfclosed"
};
Enumeration description
connecting The TCP connection has not yet been established.
open The TCP connection is established and communication is possible.
closing The TCP connection is going through the closing handshake, or the close() method has been invoked.
closed The TCP connection has been closed or could not be opened.
halfclosed The TCP connection has been "halfclosed", which means that it is not possible to send data but it is still possible to received.

A. Acknowledgements

Many thanks to Robin Berjon for making our lives so much easier with his cool tool.

B. References

B.1 Normative references

[FILE-API]
Arun Ranganathan; Jonas Sicking. File API. 25 October 2012. W3C Working Draft. URL: http://www.w3.org/TR/2012/WD-FileAPI-20121025
[HTML5]
Robin Berjon et al. HTML5. 17 December 2012. W3C Candidate Recommendation. URL: http://www.w3.org/TR/html5/
[POSTMSG]
Ian Hickson. HTML5 Web Messaging. 01 May 2012. W3C Candidate Recommendation. URL: http://www.w3.org/TR/2012/CR-webmessaging-20120501
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[TYPED-ARRAYS]
David Herman, Kenneth Russell. Typed Arrays Khronos Working Draft. (Work in progress.) URL: https://www.khronos.org/registry/typedarray/specs/latest/
[UNICODE]
The Unicode Standard. URL: http://www.unicode.org/versions/latest/
[UTF-8]
F. Yergeau. UTF-8, a transformation format of ISO 10646. IETF RFC 3629. November 2003. URL: http://www.ietf.org/rfc/rfc3629.txt
[WEBIDL]
Cameron McCormack. Web IDL. 19 April 2012. W3C Candidate Recommendation. URL: http://www.w3.org/TR/2012/CR-WebIDL-20120419/