Socket : Standard socket

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

Socket : Standard socket

The socket module is the basic module of JSRE network communication. tcp, udp, tls, dtls, net, dgram ... are all based on the socket module.

This module is designed in a synchronous mode, but with the iosched module, tcp, udp, tls, dtls all support synchronous and asynchronous mode.

The advantage of the socket module is that based on File Descriptor operations, file descriptor can be passed across tasks, but users may forget to close the socket. Since tcp, udp, tls, dtls, net, dgram uses file descriptor recycled technology to prevent users from forgetting close files, so it is recommended to use tcp, udp, tls, dtls, net, dgram modules directly.

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

var socket = require('socket');

Support

The following shows socket module APIs available for each permissions.

 User ModePrivilege Mode
socket.domain
socket.socket
socket.close
socket.bind
socket.listen
socket.accept
socket.connect
socket.disconnect
socket.send
socket.sendto
socket.recv
socket.recvfrom
socket.pending
socket.shutdown
socket.error
socket.mports 
socket.isListen
socket.isEOF
socket.sockName
socket.peerName
socket.bindToDevice
socket.setKeepAlive
socket.setNoDelay
socket.setLinger
socket.setTTL
socket.setBroadcast
socket.setReuseAddr
socket.setIPv6Only
socket.getTcpState
socket.getRecvBufferSize
socket.getSendBufferSize
socket.setRecvBufferSize
socket.setSendBufferSize
socket.addMembership
socket.dropMembership
socket.setMulticastInterface
socket.setMulticastTTL
socket.setMulticastLoop
socket.secRegion 
socket.getUdpConnAssignLocalAddr
socket.setUdpConnAssignLocalAddr
socket.addrIsIPv4
socket.addrIsIPv6

Socket Module

socket.domain(sockFd)

  • sockFd {Integer} Socket file descriptor.
  • Returns: {Integer} Returns socket domain.

Get the domain type of the specified socket file, possible values can be socket.AF_INET or socket.AF_INET6.

socket.domain(ipaddr)

  • ipaddr {String} IP address.
  • Returns: {Integer} Returns socket domain.

Get the domain type of the specified IP address, possible values can be socket.AF_INET or socket.AF_INET6.

This function is available in EdgerOS 1.10.1 and above.

socket.socket(domain, type)

  • domain {Integer} Protocol domain.
  • type {Integer} Protocol type.
  • Returns: {Integer} Returns socket file descriptor.

Create a socket, the domain can be socket.AF_INET or socket.AF_INET6. type can be:

DefinitionDescription
socket.SOCK_STREAMTCP socket.
socket.SOCK_DGRAMUDP socket.

If return value is negative, you can use console.log(sys.error(sys.errno)) to display the error message.

Example

// Create a UDP socket.
var sockFd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);

socket.close(sockFd)

  • sockFd {Integer} Socket file descriptor.

Close socket. Application must call this interface to reclaim the file descriptor unless the file descriptor has been passed to another task and is closed by another task.

socket.bind(sockFd, sockaddr)

  • sockFd {Integer} Socket file descriptor.
  • sockaddr {Object} Local address.
  • Returns: {Boolean} Whether the operation was successful.

sockaddr includes following items:

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

The socket.bind() function shall assign a local socket address. Return true if successful, false otherwise. If the port is 0, the system automatically assigns a port. The port number assigned by the system can be obtained through the socket.sockName() function.

Example

// Bind to 2049 port
socket.bind(sockFd, { 
  domain: socket.AF_INET, 
  addr: '0.0.0.0', 
  port: 2049 
});

The socket module provides a dedicated address generation function: socket.sockaddr() and socket.sockaddr6().

Example

// Bind to 2049 port
socket.bind(sockFd, socket.sockaddr('0.0.0.0', 2049));

// Bind to 2049 port (IPv6)
var scope = 0;
socket.bind(sockFd, socket.sockaddr6('::', 2049, scope));

The socket module provides some special IP address string definitions, including:

DefinitionIP
socket.INADDR_NONE'255.255.255.255'.
socket.INADDR_LOOPBACK'127.0.0.1'.
socket.INADDR_ANY'0.0.0.0';
socket.INADDR_BROADCAST'255.255.255.255';
socket.IN6ADDR_ANY'::';
socket.IN6ADDR_LOOPBACK'::1';
socket.IN6ADDR_NODELOCAL_ALLNODES'ff01::1';
socket.IN6ADDR_LINKLOCAL_ALLNODES'ff02::1';
socket.IN6ADDR_LINKLOCAL_ALLROUTERS'ff01::2';

Example

// Bind to 2049 port
socket.bind(sockFd, socket.sockaddr(socket.INADDR_ANY, 2049));

socket.listen(sockFd[, backlog])

  • sockFd {Integer} Socket file descriptor.
  • backlog {Integer} Number of outstanding connections. default: 5.
  • Returns: {Boolean} Whether the operation was successful.

The socket.listen() function shall mark a connection-mode socket, specified by the sockFd argument, as accepting connections.

Example

// Tcp server
var sockFd = socket.socket(socket.AF_INET, socket.SOCK_STREAM);

socket.bind(sockFd, socket.sockaddr(socket.INADDR_ANY, 2049));
socket.listen(sockFd, 3);

socket.accept(sockFd[, remoteAddr[, timeout]])

  • sockFd {Integer} Socket file descriptor.
  • remoteAddr {Object} Remote connector address. default: no need to get.
  • timeout {Integer} Wait timeout in milliseconds. default: undefined means wait forever.
  • Returns: {Integer} A new socket descriptor, negative on error.

The socket.accept() function shall extract the first connection on the queue of pending connections, create a new socket with the same socket type protocol and address family as the specified socket, and allocate a new file descriptor for that socket.

Example

var remoteAddr = {};
var newFd = socket.accept(sockFd, remoteAddr);
if (newFd > 0) {
  console.log('Remote connector is:', remoteAddr);
  // remoteAddr has: domain, addr, port member.
}

socket.connect(sockFd[, remoteAddr[, timeout]])

  • sockFd {Integer} Socket file descriptor.
  • remoteAddr {Object} Remote address.
  • timeout {Integer} Synchronous connection time to wait in milliseconds, default: undefined means timeout with default connect timeout setting.
  • Returns: {Boolean} Whether the operation was successful.

The socket.connect() function shall attempt to make a connection on a connection-mode socket or to set or reset the peer address of a connectionless-mode socket.

Example

var addr = socket.sockaddr('192.168.0.1', 2049);
var res = socket.connect(sockFd, addr, 2000);
if (!res) {
  console.log('connect error:', sys.error());
}

socket.disconnect(sockFd)

  • sockFd {Integer} UDP socket file descriptor.
  • Returns: {Boolean} Whether the operation was successful.

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

socket.send(sockFd, string[, timeout])

  • sockFd {Integer} Socket file descriptor.
  • 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 socket.send() function shall initiate transmission of a message from the specified socket to its peer.

Example

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

socket.send(sockFd, buffer[, offset[, length[, timeout]]])

  • sockFd {Integer} Socket file descriptor.
  • 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 socket.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 = socket.send(sockFd, buf);
if (num < 0) {
  console.log('send error:', sys.error());
}

socket.send(sockFd, array[, timeout])

  • sockFd {Integer} Socket file descriptor.
  • 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 socket.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 = socket.send(sockFd, [buf1, buf2]);
if (num < 0) {
  console.log('send error:', sys.error());
}

socket.sendto(sockFd, remoteAddr, string[, timeout])

  • sockFd {Integer} Socket file descriptor.
  • 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 socket.sendto() function shall send a message through a connection-mode or connectionless-mode socket.

Example

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

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

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

  • sockFd {Integer} Socket file descriptor.
  • remoteAddr {Object} Remote address.
  • buffer {Buffer} Write data buffer.
  • offset {Integer} Buffer offset. default:0.
  • length {Integer} Write length. default:buffer.length.
  • Returns: {Integer} The number of bytes actually sent, negative error.

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

Example

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

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

socket.sendto(sockFd, remoteAddr, array[, timeout])

  • sockFd {Integer} Socket file descriptor.
  • 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 socket.sendto() function shall send a message through a connection-mode or connectionless-mode socket.

Example

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

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

socket.recv(sockFd, buffer[, offset[, length[, timeout]]])

  • sockFd {Integer} Socket file descriptor.
  • 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 socket.recv() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connected sockets because it does not permit the application to retrieve the source address of received data.

Example

var buf = new Buffer(1024);

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

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

  • sockFd {Integer} Socket file descriptor.
  • 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 socket.recvfrom() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connectionless-mode sockets because it permits the application to retrieve the source address of received data.

Example

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

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

socket.pending(sockFd)

  • sockFd {Integer} Socket file descriptor.
  • Returns: {Integer} The number of bytes in socket buffer.

Get the number of readable bytes in the socket buffer.

Example

var num = socket.pending(sockFd);
if (num > 0) {
  socket.recv(sockFd, buf);
}

socket.shutdown(sockFd[, how])

  • sockFd {Integer} Socket file descriptor.
  • how {String} Type of shutdown. default: 'rw'.
  • Returns: {Boolean} Whether the operation was successful.

The socket.shutdown() function shall cause all or part of a full-duplex connection on the socket associated with the file descriptor socket to be shut down.

Argument how can be:

DefinitionDescription
rDisables further receive operations.
wDisables further send operations.
rwDisables further send and receive operations.

Example

// Shutdown read / write
socket.shutdown(sockFd);

// Shutdown write.
socket.shutdown(sockFd, 'w');

socket.error(sockFd)

  • sockFd {Integer} Socket file descriptor.
  • 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 = socket.error(sockFd);
if (errno) {
  console.log('socket error:', sys.error(errno));
}

socket.mports(sockFd, mports)

  • sockFd {Integer} Listen socket file descriptor.
  • mports {Integer} Number of consecutive ports to be added.

This function can set a LISTEN state tcp file descriptor for multi-port listening, starting with the port when bind(), set the number of additional listening continuous ports.

Example

// Bind to 1024 port
socket.bind(sockFd, { 
  domain: socket.AF_INET, 
  addr: '0.0.0.0', 
  port: 1024 
});
socket.mports(sockFd, 5); // add listen ports: 1025, 1026, 1027, 1028, 1029

socket.isListen(sockFd)

  • sockFd {Integer} Socket file descriptor.
  • Returns: {Boolean} Whether this socket is a listen socket.

Get sockFd socket whether is a listen socket.

Example

socket.listen(sockFd);

// true
var res = socket.isListen(sockFd);

socket.isEOF()

  • Returns: {Boolean} Whether the TCP socket receives complete data. (EOF)

This function is used to judge whether the TCP connection has received complete data. This function must follow the recv and recvfrom functions. When these two functions return a negative number, it means that the TCP connection is disconnected. You can judge whether the reception is complete through the isEOF function. This function is valid on EdgerOS 2.0.0 and above.

Example

var num = socket.recv(...);
if (num < 0) {
  if (socket.isEOF()) {
    console.log('receives complete data');
  }
}

socket.sockName(sockFd)

  • sockFd {Integer} Socket file descriptor.
  • Returns: {Object} Local sockaddr.

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

Example

socket.bind(sockFd, socket.sockaddr('0.0.0.0', 2049));

var saddr = socket.sockName(sockFd);
console.log(saddr);

socket.peerName(sockFd)

  • sockFd {Integer} Socket file descriptor.
  • Returns: {Object} Remote sockaddr.

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

Example

socket.connect(sockFd, socket.sockaddr('192.168.0.2', 2049));

var saddr = socket.peerName(sockFd);
console.log(saddr);

socket.bindToDevice(sockFd[, ifname])

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

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

Example

socket.bindToDevice(sockFd, 'en1');

socket.setKeepAlive(sockFd, enable[, idle[, interval[, count]]])

  • sockFd {Integer} Socket file descriptor.
  • enable {Boolean} Whether to enable the keepalive.
  • idle {Integer} The time (in milliseconds) the connection needs to remain idle before TCP starts sending keepalive probes. If enable is true, must have this parameter.
  • interval {Integer} The time (in milliseconds) between individual keepalive probes. default: idle.
  • count {Integer} The maximum number of keepalive probes TCP should send before dropping the connection. default: 3.
  • Returns: {Boolean} Whether the operation was successful.

Keeps connections active by enabling the periodic transmission of messages, only TCP support keepalive setting.

Example

socket.setKeepAlive(sockFd, true, 6000);

socket.setNoDelay(sockFd, enable)

  • sockFd {Integer} Socket file descriptor.
  • enable {Boolean} Whether to enable the no delay.
  • Returns: {Boolean} Whether the operation was successful.

For TCP NO DEALY, please refer to Nagle's Algorithm and Delayed ACK related articles, which are not described here. If TCP is used for interactive commands, it is recommended to enable.

Example

socket.setNoDelay(sockFd, true);

socket.setLinger(sockFd, linger)

  • sockFd {Integer} Socket file descriptor.
  • linger {Object} Liger option.
  • Returns: {Boolean} Whether the operation was successful.

linger includes following items:

  • onoff {Boolean} On: true, Off: false:.
  • time {Integer} Linger time expires in seconds.

If linger.onoff is nonzero and linger.time is nonzero, then the kernel will linger when the socket is closed. That is, if there is any data still remaining in the socket send buffer, the process is put to sleep until either: all the data is sent and acknowledged by the peer TCP, or the linger time expires.

Example

socket.setLinger(sockFd, { onoff: true, time: 0 });

socket.setTTL(sockFd, timeToLive)

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

Changes the specified socket TTL value of the IP header.

Example

socket.setTTL(sockFd, 64);

socket.setBroadcast(sockFd, enable)

  • sockFd {Integer} Socket file descriptor.
  • enable {Boolean} Whether to enable broadcast.
  • Returns: {Boolean} Whether the operation was successful.

Permits sending of broadcast messages, for UDP, RAW(in futrue) only.

Example

socket.setBroadcast(sockFd, true);

socket.setReuseAddr(sockFd, enable)

  • sockFd {Integer} Socket file descriptor.
  • enable {Boolean} Whether to enable reuse address.
  • Returns: {Boolean} Whether the operation was successful.

Specifies that the rules used in validating addresses supplied to socket.bind() should allow reuse of local addresses.

Example

socket.setReuseAddr(sockFd, true);

socket.setIPv6Only(sockFd, enable)

  • sockFd {Integer} Socket file descriptor.
  • enable {Boolean} Whether to only enable IPv6.
  • Returns: {Boolean} Whether the operation was successful.

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

Example

socket.setIPv6Only(sockFd, false);

socket.getTcpState(sockFd)

  • sockFd {Integer} Socket file descriptor.
  • Returns: {Integer} TCP state, negative on error.

Get the current TCP connection state. Only TCP socket can call this function.

The return value will be one of the following values:

  • socket.TCP_CLOSED
  • socket.TCP_LISTEN
  • socket.TCP_SYN_SENT
  • socket.TCP_SYN_RCVD
  • socket.TCP_ESTABLISHED
  • socket.TCP_FIN_WAIT_1
  • socket.TCP_FIN_WAIT_2
  • socket.TCP_CLOSE_WAIT
  • socket.TCP_CLOSING
  • socket.TCP_LAST_ACK
  • socket.TCP_TIME_WAIT

Example

var state = socket.getTcpState(sockFd);

socket.getRecvBufferSize(sockFd)

  • sockFd {Integer} Socket file descriptor.
  • Returns: {Integer} Receive buffer size, negative on error.

Get current receive buffer size in bytes.

socket.getSendBufferSize(sockFd)

  • sockFd {Integer} Socket file descriptor.
  • Returns: {Integer} Send buffer size, negative on error.

Get current send buffer size in bytes.

socket.setRecvBufferSize(sockFd, size)

  • sockFd {Integer} Socket file descriptor.
  • 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.

socket.setSendBufferSize(sockFd, size)

  • sockFd {Integer} Socket file descriptor.
  • 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.

socket.addMembership(sockFd, multicastAddr[, multicastInterface[, sourceAddr]])

  • sockFd {Integer} Socket file descriptor.
  • 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 socket.addMembership() to join an multicast group on a interface.

Example

socket.addMembership(sockFd, '224.0.1.222', 'en1');

socket.dropMembership(sockFd, multicastAddr[, multicastInterface[, sourceAddr]])

  • sockFd {Integer} Socket file descriptor.
  • 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 socket.dropMembership() to leave an multicast group on a interface.

Example

socket.dropMembership(sockFd, '224.0.1.222', 'en1');

socket.setMulticastInterface(sockFd, multicastInterface)

  • sockFd {Integer} Socket file descriptor.
  • multicastInterface {String} Multicast network interface name.
  • Returns: {Boolean} Whether the operation was successful.

Set the specified socket multicast network interface.

Example

socket.setMulticastInterface(sockFd, 'wl3');

socket.setMulticastTTL(sockFd, timeToLive)

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

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

Example

socket.setMulticastTTL(sockFd, 8);

socket.setMulticastLoop(sockFd, enable)

  • sockFd {Integer} Socket file descriptor.
  • enable {Boolean} Whether to enable multicast loop.
  • Returns: {Boolean} Whether the operation was successful.

Set the specified socket whether to allow multicast loop.

Example

socket.setMulticastLoop(sockFd, false);

socket.secRegion(sockFd[, newRegion])

  • sockFd {Integer} Socket file descriptor.
  • newRegion {Integer} New security region.
  • Returns: {Integer} This socket security region.

Get or set the specified socket security region.

socket.getUdpConnAssignLocalAddr(sockFd)

  • sockFd {Integer} UDP socket file descriptor.
  • 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.

socket.setUdpConnAssignLocalAddr(sockFd, enable)

  • sockFd {Integer} UDP socket file descriptor.
  • 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.

Other Constant

socket.IPPROTO_IP

  • {Integer} IP packet type.

socket.IPPROTO_IPV6

  • {Integer} IPv6 packet type.

socket.IPPROTO_TCP

  • {Integer} TCP packet type.

socket.IPPROTO_UDP

  • {Integer} UDP packet type.
文档内容是否对您有所帮助?
有帮助
没帮助