UDP : UDP communication with multicast support

更新时间:
2024-05-13
下载文档

UDP : UDP communication with multicast support

The Udp module is based on socket module, which makes UDP communication more convenient. This module is relatively low-level, it is recommended to use the dgram module to operate UDP communication.

User can use the following code to import the Udp module.

var Udp = require('udp');

Support

The following shows Udp module APIs available for each permissions.

 User ModePrivilege Mode
Udp.create
Udp.createServer
Udp.createClient
Udp.createByFd
udp.sockFd
udp.bind
udp.connect
udp.disconnect
udp.send
udp.sendto
udp.recv
udp.recvfrom
udp.pending
udp.error
udp.close
udp.flyAway
udp.sockName
udp.peerName
udp.bindToDevice
udp.setTTL
udp.setReuseAddr
udp.setBroadcast
udp.setIPv6Only
udp.getRecvBufferSize
udp.getSendBufferSize
udp.setRecvBufferSize
udp.setSendBufferSize
udp.addMembership
udp.dropMembership
udp.setMulticastInterface
udp.setMulticastTTL
udp.setMulticastLoop
udp.getConnAssignLocalAddr
udp.setConnAssignLocalAddr

Udp Class

Udp.create([domain])

  • domain {Integer} Address domain: socket.AF_INET or socket.AF_INET6. default: socket.AF_INET.
  • Returns: {Object} Udp object.

Create a UDP object, this object can be both server and client. This function is valid on EdgerOS 2.0.0 and above.

Example

var udp = Udp.create();
if (udp) {
  udp.bind(...); // Bind to local address.
  //Or:
  udp.connect(...); // Connect to remote address.
}

Udp.createServer(sockaddr[, reuseAddr[, dev]])

  • sockaddr {Object} Local address.
  • reuseAddr {Boolean} Whether to enable reuse the address.
  • dev {String} The network interface you want to bind. default: not bind.
  • Returns: {Object} Udp object.

sockaddr includes following items:

  • domain {Integer} Address domain: socket.AF_INET or socket.AF_INET6.
  • addr {String} Address.
  • port {Integer} Port.

Create a UDP server and bind to the specified address. If the port is 0, the system automatically assigns a port. The port number assigned by the system can be obtained through the udp.sockName() function.

EdgerOS 1.6.5 and later versions, domain can use Udp.AF_INET and Udp.AF_INET6; EdgerOS 1.10.1 and later versions, The domain member can be omitted.

Example

var saddr = Udp.sockaddr(Udp.INADDR_ANY, 2049);
var udp = Udp.createServer(saddr);

Udp.createClient(sockaddr)

  • sockaddr {Object} Remote address.
  • Returns: {Object} Udp object.

Create a UDP client and connects to the specified remote host. Returns undefined if no route is connected to the remote.

Example

var saddr = Udp.sockaddr('192.168.0.3', 2049);
var udp = Udp.createClient(saddr);
if (!udp) {
  console.log('connect error:', sys.error());
}

Udp.createByFd(sockFd)

  • sockFd {Integer} Socket file descriptor, MUST udp socket.
  • Returns: {Object} Udp object.

Create a udp object with socket file descriptor, mainly used to multitasking UDP server.

Example

var udp = Udp.createByFd(sockFd);

Udp Object

udp.sockFd

  • {Integer}

The udp object socket file descriptor. The iosched module can use this descriptor for event detection.

udp.bind(saddr)

  • saddr {Object} Local address.
  • Returns: {Boolean} Whether succeed.

UDP bind specified local address. This function is valid on EdgerOS 2.0.0 and above.

udp.connect(saddr)

  • saddr {Object} Remote address.
  • Returns: {Boolean} Whether succeed.

UDP set remote destination address. UDP connect will automatically bind the appropriate local address, so that if the information cannot be received when the route changes, you can bind this udp object to socket.INADDR_ANY again.

udp.disconnect()

  • Returns: {Boolean} Whether succeed.

UDP disconnect, equivalent to udp object clear remote address set. This function is valid on EdgerOS 2.0.0 and above.

udp.send(string[, timeout])

  • string {String} String to be send.
  • timeout {Integer} Wait timeout in milliseconds. default: undefined means wait forever.
  • Returns: {Integer} The number of bytes actually sent, negative error.

The udp.send() function shall initiate transmission of a message from the specified socket to its peer.

Example

var num = udp.send('Hello Packet!');
if (num < 0) {
  console.log('send error:', sys.error());
}

udp.send(buffer[, offset[, length[, timeout]]])

  • buffer {Buffer} Write data buffer.
  • offset {Integer} Buffer offset. default:0.
  • length {Integer} Write length. default:buffer.length.
  • timeout {Integer} Wait timeout in milliseconds. default: undefined means wait forever.
  • Returns: {Integer} The number of bytes actually sent, negative error.

The udp.send() function shall initiate transmission of a message from the specified socket to its peer.

Example

var buf = new Buffer([1, 2, 3]);

var num = udp.send(buf);
if (num < 0) {
  console.log('send error:', sys.error());
}

udp.send(array[, timeout])

  • array {Array} Buffer array.
  • timeout {Integer} Wait timeout in milliseconds. default: undefined means wait forever.
  • Returns: {Integer} The number of bytes actually sent, negative error.

The udp.send() function shall initiate transmission of a message from the specified socket to its peer.

Example

var buf1 = new Buffer([1, 2, 3]);
var buf2 = new Buffer([4, 5, 6]);
var num = udp.send([buf1, buf2]);
if (num < 0) {
  console.log('send error:', sys.error());
}

udp.sendto(remoteAddr, string[, timeout])

  • remoteAddr {Object} Remote address.
  • string {String} String to be send.
  • timeout {Integer} Wait timeout in milliseconds. default: undefined means wait forever.
  • Returns: {Integer} The number of bytes actually sent, negative error.

The udp.sendto() function shall send a message through a udp socket.

Example

var remoteAddr = Udp.sockaddr('192.168.0.2', 2049);

// Udp sendto.
var num = udp.sendto(remoteAddr, 'Hello Packet!');
if (num < 0) {
  console.log('sendto error:', sys.error());
}

udp.sendto(remoteAddr, buffer[, offset[, length[, timeout]]])

  • remoteAddr {Object} Remote address.
  • buffer {Buffer} Write data buffer.
  • offset {Integer} Buffer offset. default:0.
  • length {Integer} Write length. default:buffer.length.
  • timeout {Integer} Wait timeout in milliseconds. default: undefined means wait forever.
  • Returns: {Integer} The number of bytes actually sent, negative error.

The udp.sendto() function shall send a message through a udp socket.

Example

var remoteAddr = Udp.sockaddr('192.168.0.2', 2049);
var buf = new Buffer([1, 2, 3]);

// Udp sendto.
var num = udp.sendto(remoteAddr, buf);
if (num < 0) {
  console.log('sendto error:', sys.error());
}

udp.sendto(remoteAddr, array[, timeout])

  • remoteAddr {Object} Remote address.
  • array {Array} Buffer array.
  • timeout {Integer} Wait timeout in milliseconds. default: undefined means wait forever.
  • Returns: {Integer} The number of bytes actually sent, negative error.

The udp.sendto() function shall send a message through a connection-mode or connectionless-mode socket.

Example

var remoteAddr = udp.sockaddr('192.168.0.2', 2049);
var buf1 = new Buffer([1, 2, 3]);
var buf2 = new Buffer([4, 5, 6]);

// Udp sendto.
var num = udp.sendto(remoteAddr, [buf1, buf2]);
if (num < 0) {
  console.log('sendto error:', sys.error());
}

udp.recv(buffer[, offset[, length[, timeout]]])

  • buffer {Buffer} Receive buffer.
  • offset {Integer} Buffer offset. default:0.
  • length {Integer} Receive length limit. default:buffer.length.
  • timeout {Integer} Wait timeout in milliseconds. default: undefined means wait forever.
  • Returns: {Integer} The number of bytes actually receive, negative error.

The udp.recv() function shall receive a message from udp socket.

Example

var buf = new Buffer(1024);

var num = udp.recv(buf);
if (num < 0) {
  console.log('recv error:', sys.error());
}

udp.recvfrom(remoteAddr, buffer[, offset[, length[, timeout]]])

  • remoteAddr {Object} Remote address.
  • buffer {Buffer} Receive buffer.
  • offset {Integer} Buffer offset. default:0.
  • length {Integer} Receive length limit. default:buffer.length.
  • timeout {Integer} Wait timeout in milliseconds. default: undefined means wait forever.
  • Returns: {Integer} The number of bytes actually receive, negative error.

The udp.recvfrom() function shall receive a message from udp socket.

Example

var remoteAddr = {};
var buf = new Buffer(1024);

var num = udp.recvfrom(remoteAddr, buf);
if (num < 0) {
  console.log('recvfrom error:', sys.error());
}

udp.pending()

  • Returns: {Integer} The number of bytes in udp buffer.

Get the number of readable bytes in the udp buffer of next packet.

Example

var num = udp.pending();
if (num > 0) {
  var buf = new Buffer(num);
  udp.recv(buf);
}

udp.error()

  • Returns: {Integer} Last socket errno.

Get socket error status and clears it (set to zero). most like (C language):

getsockopt(sockFd, SOL_SOCKET, SO_ERROR, (void *)&err, &len);

Example

var errno = udp.error();
if (errno) {
  console.log('socket error:', sys.error(errno));
}

udp.close()

Close this udp and reclaiming file descriptors. If user forgets to call this function, the file descriptor is automatically reclaimed when the object is destroyed.

udp.flyAway()

This function is only used in multitasking mode. Clear the object internal file descriptor and do not recycle the file descriptor. This method is used for file descriptor delivery between multitasking, to prevent system errors from reclaiming file descriptors.

Example

  • main.js
var udp = ...();

// Send file descriptor to other task.
Task.send(otherTask.id(), { sockFd: udp.sockFd });

// MUST Call flyAway() and cannot use this object again.
udp.flyAway();
  • task.js
var msg = Task.recv();

// Create a udp object by sockFd.
var udp = Udp.createByFd(msg.sockFd);

udp.sockName()

  • Returns: {Object} Local sockaddr.

The udp.sockName() function shall retrieve the locally-bound name of the specified socket.

Example

var saddr = udp.sockName();
console.log(saddr);

udp.peerName()

  • Returns: {Object} Remote sockaddr.

The udp.peerName() function shall retrieve the peer address of the specified socket.

Example

var saddr = udp.peerName();
console.log(saddr);

udp.bindToDevice([ifname])

  • ifname {String} Network interface name. default: all network interface.
  • Returns: {Boolean} Whether the operation was successful.

The udp.bindToDevice() function binds the network sending and receiving to the specified network interface, and the data packet is only allowed to be sent and received using this network interface.

Example

udp.bindToDevice('en1');

udp.setTTL(timeToLive)

  • timeToLive {Integer} IP TTL: 0 ~ 255.
  • Returns: {Boolean} Whether the operation was successful.

Changes the specified udp TTL value of the IP header.

Example

udp.setTTL(64);

udp.setReuseAddr(enable)

  • enable {Boolean} Whether to enable reuse the address.
  • Returns: {Boolean} Whether the operation was successful.

When true socket.bind() will reuse the address, even if another process has already bound a socket on it.

udp.setBroadcast(enable)

  • enable {Boolean} Whether to enable broadcast.
  • Returns: {Boolean} Whether the operation was successful.

Permits sending of broadcast messages.

Example

udp.setBroadcast(true);

udp.setIPv6Only(enable)

  • enable {Boolean} Whether to only enable IPv6.
  • Returns: {Boolean} Whether the operation was successful.

If this flag is set to true, then the udp is re‐stricted to sending and receiving IPv6 packets only.

Example

udp.setIPv6Only(false);

udp.getRecvBufferSize()

  • Returns: {Integer} Receive buffer size, negative on error.

Get current receive buffer size in bytes.

udp.getSendBufferSize()

  • Returns: {Integer} Send buffer size, negative on error.

Get current send buffer size in bytes.

udp.setRecvBufferSize(size)

  • size {Integer} Receive buffer size. Must be between 1024bytes and 16Mbytes.
  • Returns: {Boolean} Whether the operation was successful.

Set current receive buffer size in bytes.

udp.setSendBufferSize(size)

  • size {Integer} Send buffer size. Must be between 1024bytes and 16Mbytes.
  • Returns: {Boolean} Whether the operation was successful.

Set current send buffer size in bytes.

udp.addMembership(multicastAddr[, multicastInterface[, sourceAddr]])

  • multicastAddr {String} Multicast address.
  • multicastInterface {String} Multicast network interface name. default: all interface.
  • sourceAddr {String} Only receive multicast packets sent by the specified source address. default: all packets.
  • Returns: {Boolean} Whether the operation was successful.

Use the udp.addMembership() to join an multicast group on a interface.

Example

udp.addMembership('224.0.1.222', 'en1');

udp.dropMembership(multicastAddr[, multicastInterface[, sourceAddr]])

  • multicastAddr {String} Multicast address.
  • multicastInterface {String} Multicast network interface name. default: all interface.
  • sourceAddr {String} Only receive multicast packets sent by the specified source address. default: all packets.
  • Returns: {Boolean} Whether the operation was successful.

Use the udp.dropMembership() to leave an multicast group on a interface.

Example

udp.dropMembership('224.0.1.222', 'en1');

udp.setMulticastInterface(multicastInterface)

  • multicastInterface {String} Multicast network interface name.
  • Returns: {Boolean} Whether the operation was successful.

Set the specified udp multicast network interface.

Example

udp.setMulticastInterface('wl3');

udp.setMulticastTTL(timeToLive)

  • timeToLive {Integer} IP TTL: 0 ~ 255.
  • Returns: {Boolean} Whether the operation was successful.

Changes the specified udp TTL value of the multicast IP header.

Example

udp.setMulticastTTL(8);

udp.setMulticastLoop(enable)

  • enable {Boolean} Whether to enable multicast loop.
  • Returns: {Boolean} Whether the operation was successful.

Set the specified udp whether to allow multicast loop.

Example

udp.setMulticastLoop(false);

udp.getConnAssignLocalAddr()

  • Returns: {Boolean} Whether to assign a local address when UDP connects.

Get whether to assign a local address when UDP connects. This function is valid on EdgerOS 2.0.0 and above.

udp.setUdpConnAssignLocalAddr(enable)

  • enable {Boolean} Whether to assign a local address when UDP connects.
  • Returns: {Boolean} Whether the operation was successful.

Set whether to assign a local address when UDP connects. This function is valid on EdgerOS 2.0.0 and above.

Synchronous to asynchronous

JSRE provides a synchronous multitasking model. Like other language environments, it also provides an asynchronous processing model. You can choose any way to develop application, even in one application, depending on the characteristics of the different transactions, you can using different methods at one application.

If you are very familiar with asynchronous development, the following method here can convert synchronization to asynchronous.

Server

Example

var EventEmitter = require('events');
var Udp = require('udp');
var iosched = require('iosched');

var saddr = Udp.sockaddr(Udp.INADDR_ANY, 2049);
var server = Udp.createServer(saddr);

function onMessage(server, client, buffer, num) {
  console.log('Client:', client.addr, 'Say:', buffer.toString(num));
}

EventEmitter.inherits(server);
server.on('message', onMessage);

server.revent = iosched.event(iosched.READ, server.sockFd,
(server) => {
  var client = {};
  var buffer = new Buffer(4096);
  var num = server.recvfrom(client, buffer);
  if (num > 0) {
    server.emit('message', server, client, buffer, num);
    return true;
  } else {
    console.log('Error:', sys.error());
    return false;
  }
}, undefined, server);

iosched.add(server.revent);

while (true) {
  iosched.poll();
}

Client

Example

var Udp = require('udp');

var saddr = Udp.sockaddr('192.168.0.2', 2049);
var client = Udp.createClient(saddr);
if (client) {
  client.send('Hello I am client ^_^');
  client.send('Goodbye!');
  client.close();
}

Udp Module Constant

Udp.AF_INET

  • {Integer} 2

Udp.AF_INET6

  • {Integer} 10

Udp.INADDR_NONE

  • {String} '255.255.255.255'

Udp.INADDR_LOOPBACK

  • {String} '127.0.0.1'

Udp.INADDR_ANY

  • {String} '0.0.0.0'

Udp.INADDR_BROADCAST

  • {String} '255.255.255.255'

Udp.IN6ADDR_ANY

  • {String} '::'

Udp.IN6ADDR_LOOPBACK

  • {String} '::1'

Udp.IN6ADDR_NODELOCAL_ALLNODES

  • {String} 'ff01::1'

Udp.IN6ADDR_LINKLOCAL_ALLNODES

  • {String} 'ff02::1'

Udp.IN6ADDR_LINKLOCAL_ALLROUTERS

  • {String} 'ff01::2'
文档内容是否对您有所帮助?
有帮助
没帮助