This module supports sending and receiving UDP (datagram) messages. Unlike TCP sockets, UDP is 'connectionless', meaning that each message is sent as a unit to recipient. Also, unlike TCP, delivery is not guaranteed, so this should be used only in situations where losing messages is not a problem.
This module is fashioned after the Node dgram module. The main difference is that this module provides support for send and receive data types so that a user of the module can just specify those types and not have to parse the received data.
A simple example that listens for messages on port 8084 and prints out any that arrive:
var UDPSocket = require('@accessors-modules/udp-socket');
var socket = UDPSocket.createSocket();
socket.on('message', function(message) {
print('Received from web socket: ' + message);
});
socket.bind(8084);
Functions
- createSocket(type, callback): Create a socket of type "udp4" or "udp6" and invoke the (optional) callback once created.
- supportedReceiveTypes(): Return an array of the types that can be received over the socket supported by the current host.
- supportedSendTypes(): Return an array of the types that can be received over the socket supported by the current host.
Socket Class
An instance of this class, created with new, is a socket client that can send or receive messages
to a server at the host and port to the constructor.
The constructor takes one argument:
- type: One of "udp4" or "udp6" for IPv4 or IPv6 sockets.
The Socket object is an event emitter that emits the following events:
- listening: Emits on listening.
- message: Emits a received message, interpreted according to the specified receive type.
- close: Emits on closing.
- error: Emits with a message argument when an error occurs.
To receive messages, call bind() on a Socket object. To send messages, call send().
A Socket object has the following functions:
- bind(port, address, callback): Start listening on the specified port and network interface address (optional, defaults to "0.0.0.0", which means to listen on all interfaces). If a callback function is given, it will be invoked when listening.
- close(): Close the socket.
- send(data, port, hostname, callback): Send the specified data to the specified host and port. If a callback function is provided, that function will be called upon completion of the send (note that receipt of the message, however, is not assured).
- setReceiveType(type): Set the receive type. The argument should be a string matching one of the types returned by supportedReceiveTypes().
- setSendType(type): Set the send type. The argument should be a string matching one of the types returned by supportedSendTypes().
See https://ptolemy.berkeley.edu/accessors/wiki/Modules/UDPSocket for further information.
Back to Optional JavaScript Modules