This API provides interfaces to raw UDP sockets, TCP Client sockets and TCP Server sockets.

Introduction

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

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.

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

Security and privacy considerations

This API must be only exposed to trusted content.

Interface UDPSocket

The UDPSocket interface defines the attributes and methods for a UDP socket

        // 
        // This example shows a a simple implementation of UPnP-SSDP M-SEARCH discovery using a multicast UDPSocket 
        //
        
        // Create a UDP socket
        var mySocket = new UDPSocket (); 
        
        // Send 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;
        
        var socketRequest = mySocket.sendUDP(MSearch, SSDPMulticastAddress, SSDPMulticastPort);
        
        socketRequest.onsuccess = function() { 
          console.log('M-SEARCH Sent!'); 
        }
        socketRequest.onerror = function(e) {
          console.error(e.target.error.name);
        }
        
        
        // Receive M-SEARCH responses          
        mysocket.onreceivedudp = function (receivedUDPEvent) { 
          console.log(“Peer address: ” + receivedUDPEvent.peerAddress + “ Peer port: “ + 
                      receivedUDPEvent.peerPort +  " Received data" + receivedUDPEvent.data);
        };       
        
      
        // 
        // 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 SSDP multicast address and port
        var mySocket = new UDPSocket ({"localAddress":SSDPMulticastAddress, "localPort":SSDPMulticastPort});    
        
        // Receive SSDP NOTFIY         
        mysocket.onreceivedudp = function (receivedUDPEvent) { 
          console.log(“Peer address: ” + receivedUDPEvent.peerAddress + “ Peer port: “ + 
                      receivedUDPEvent.peerPort +  " Received data" + receivedUDPEvent.data);
        };       
        
      
readonly attribute UDPCreateOptions options
The socket create options.
readonly attribute DOMString localAddress
This attribute contains the local IPv4/6 address that the UDPSocket object is bound to. The application can bind the socket to a specific local address through the UDPSocket constructor's localAddress argument. If this argument is ommitted or null the user agent binds the socket to any available local IPv4/6 address.
readonly attribute unsigned short localPort
This attribute contains the local port that the UDPSocket object is bound to. The application can bind the socket to a specific local port through the UDPSocket constructor's localPort argument. If this argument is ommitted or null the user agent binds the socket to any available local port.
attribute EventHandler onreceivedudp
Event handler for received data.
attribute EventHandler ondrainudp
Event handler for ondrainudp event.
SocketRequest sendUDP()

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

Throws DOMException InvalidAccessError if any input parameter is not compatible with the expected type for that parameter.

any data
The data to write. Data type is defined through the UDPSocket constructor options binaryType attribute.
DOMString peerAddress
The address of the remote machine.
unsigned short peerPort
The port of the remote machine.
void suspend()

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

void resume()

Resume reading incoming UDPdata and invoking onreceivedudp as usual.

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

  1. If the localAddress argument is absent or null then bind the socket to any available local IPv4/6 address. Otherwise, if the requested local address is free or if it is in use and the options.addressReuse attribute is true then bind the socket to the requested local address. Else, throw an InvalidAccessError exception and abort these steps.
  2. If the localPort argument is absent or null 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 then bind the socket to the requested local port. Else, throw an InvalidAccessError exception and abort these steps.
  3. Create a new UDPSocket object and set the localAddress and localPort attributes according to the steps above. Set the options attribute according to the constructors options argument if it was present, else set the options attribute to the default values.
  4. Return the newly created UDPSocket object to the application.

The sendUDP method when invoked MUST run the following steps:

  1. Create a new instance of SocketRequest and:
    1. Make a request to the system to send UDP data with data passed in the data. parameter to the address and port of the recipient indicated in the peerAddress and peerPort parameters.
    2. set readyState of the SocketRequest object to 'processing'.
    3. return the SocketRequest to the caller and queue a task to monitor UDP data sending progress.
  2. If there is an error invoke the onerror event handler of the SocketRequest object.
  3. When the requests has been completed:
    1. set the readyState of the SocketRequest object to 'done'
    2. set the result of the SocketRequest object to true or false as a hint to the caller that they may either continue sending more data immediately, or may want to wait until the transport layer has transmitted buffered data that already have been written to the socket before buffering more. If result is true, then less than 64k has been buffered and it's safe to immediately write more. If result returns false, then more than 64k has been buffered, and the caller may wish to wait until the ondrain event handler has been called before buffering more data by more calls to sendUDP(). Note that this is only advisory, and the client is free to ignore it and buffer as much data as desired, but if reducing the size of buffers is important (especially for a streaming application) ondrain will be called once the previously-buffered data has been written to the network, at which point the client can resume calling sendUDP() again.
    3. invoke the onsuccess event handler of the SocketRequest.

Not sure on the result and the ondrain event handler described above. Is this relevant for sending UDP? There is no flow-control as there is for TCP but the network layer may not be able to send data fast enough. On the other hand I assume that the application have to implement buffering anyway as we can never assume that the API implementation send buffers are "unlimited" in size.

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

  1. create a new instance of ReceivedUDPEvent.
  2. set the data of the ReceivedUDPEvent to the contents of the data field of the received UDP datagram in the datatype as defined by the UDPSocket constructor's options binaryType attribute.
  3. set the peerAddress of the ReceivedUDPEvent to the source address of the received UDP datagram.
  4. set the peerPort of the ReceivedUDPEvent to the source port of the received UDP datagram.
  5. queue a task to fire an event named receivedudp with the newly created ReceivedUDPEvent 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 drainudp at the UDPSocket object.

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 handler event type
onreceivedudp receivedudp
ondrainudp drainudp

The receivedudp event SHALL implement the ReceivedUDPEvent interface.

SocketRequest Interface

The SocketRequest interface represents an ongoing operation. It provides callbacks that are called when the operation completes, as well as a reference to the operation's result. A method that initiates an operation, e.g. send UDP data via the sendUDP method in the UDPSocket interface) MUST return a SocketRequest object that can be used to monitor the progress of that operation.

readonly attribute DOMString readyState
Indicates the state of the request, with possible string values 'processing',if the request has been made and it is progressing, or 'done', if the request has been already completed.
readonly attribute DOMError? error
An error that occured during the request. Errors are as defined in [[!DOM4]].
readonly attribute any? result
Indicates the result of the request. The type depends on the sort of request, and is specified in the description of each method that returns a SocketRequest object, e.g. sendUDP method of the UDPSocket object.
attribute EventHandler onsuccess
attribute EventHandler onerror

Event handlers

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

event handler event handler event type
onsuccess success
onerror error

ReceivedUDPEvent Interface

The ReceivedUDPEvent interface represents events related to received UDP data.

readonly attribute any data
The received data. Data type is defined through the UDPSocket constructor options binaryType attribute.
readonly attribute DOMString peerAddress
The address of the remote machine.
readonly attribute unsigned short peerPort
The port of the remote machine.

Callbacks

Dictionary UDPCreateOptions

UDPsocket create options.

boolean useSecureTransport
True if socket uses SSL or TLS. Default is false.
boolean addressReuse
True allows the socket to be bound to an address that is already in use. This is for example needed for UPnP SSDP which uses a fixed multicast channel and port reserved for SSDP. Default is True.
boolean loopback
True means that data you send is looped back to your host. Default is False.
BinaryType binaryType
Data type for sent and received data. Default is "string".

Enums

BinaryType

arraybuffer
Use UInt8 array for sent and received data.
string
Use JavaScript strings for sent and received data.

Acknowledgements

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