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 (); 
        
        // 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;
        
        try {
          // Send SSDP M-SEARCH multicast message
          var moreBufferingOK = mySocket.sendUDP(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.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.
readonly attribute unsigned long bufferedAmount
This attribute contains The number of bytes which have previously been buffered by calls to sendUDP() on this socket.
attribute EventHandler onreceivedudp
Event handler for received data.
attribute EventHandler ondrainudp
Event handler for ondrainudp event.
boolean sendUDP()

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

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. 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. If there is an error and the data can not be sent throw an exception and abort these steps.
  3. If any input parameter is not compatible with the expected type for that parameter throw DOMException InvalidAccessError and abort these steps.
  4. If the data cannot be sent because it would need to be buffered but the buffer is full or if the data is too long to pass atomically through the underlying protocol,then throw DOMException InvalidStateError and abort these steps.
  5. If the data cannot be sent because the data is too long to pass atomically through the underlying protocol,then throw DOMException InvalidAccessError and abort these steps.
  6. 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 may 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 64k has been buffered and it's safe to immediately write more set the return value to true. When more than 64k has been buffered set the return value to false. This means that the caller may wish to wait before buffering more data by more calls to sendUDP() until the ondrain event handler has been called. 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.

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.

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.

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.