Next | Previous

socket

This module provides access to the underlying system socket management implementations. It is meant to be used to provide more controlled and specific operating system features and for implementing various standard and custom network protocols and specifications for which Blade does not provide a built-in implementation for.

This module defines a lot of constant that whose value complies with the operating system specification and they should be used instead of a finite value wherever available as values for these constants can change across different OS implementations.

What's a Socket

Sockets are bidrectional communication medias for information exchange between various processes within the same machine or different machines.

There are three important concepts that must important to know when working with sockets.

  1. Family: This refer to the general group of sockets that a specific protocol handled by a socket belongs to. This is any of the AF_ constants.
  2. Types: The type of communication between the two processes involved. And can only be one of SOCK_STREAM or SOCK_DGRAM.
  3. Protocol: This is to identify the variant protocol on which one or more network protocols are based on. Typically 0 or any of the IP_ constants.

A simple socket may be instanciated as follows:

import socket { Socket }
var sock = Socket()

The { Socket } in the import statement means we are only importing the Socket class and not the entire socket module. Other examples here will skip the assume you are importing just what you need out of the package but will not show the import statement.

The example above instantiates a socket without any arguments, and it is equivalent to:

Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)

You can establish a connection with another socket with a known address and port as follows:

var socket = Socket()
socket.connect('127.0.0.1', 4000)

The above example connects to the process listening at port 4000 on host with IP address 127.0.0.1. A connection is a pre-requisite to writing or reading from a socket.

After connecting to a socket, you can read and write data as follows:

var socket = Socket()
socket.connect('127.0.0.1', 4000)

var message_from_client = socket.receive()
socket.send('You sent: ' + message_from_client)

The above example simply replies the client with You sent: + whatever the client acutally sent.

Due to resource limitations, its good practice to always ensure to close sockets when done with it. Doing this is pretty simple.

socket.close()

Properties

  • SOCK_STREAM:

    stream socket

  • SOCK_DGRAM:

    datagram socket

  • SOCK_RAW:

    raw-protocol interface

  • SOCK_RDM:

    reliably-delivered message

  • SOCK_SEQPACKET:

    sequenced packet stream

  • SO_DEBUG:

    Turn on debugging info recording

  • SO_ACCEPTCONN:

    Socket has had listen()

  • SO_REUSEADDR:

    Allow local address reuse

  • SO_KEEPALIVE:

    Keep connections alive

  • SO_DONTROUTE:

    Just use interface addresses

  • SO_BROADCAST:

    Permit sending of broadcast msgs

  • SO_USELOOPBACK:

    Bypass hardware when possible

  • SO_LINGER:

    Linger on close if data present (in ticks)

  • SO_OOBINLINE:

    Leave received OOB data in line

  • SO_REUSEPORT:

    Allow local address & port reuse

  • SO_TIMESTAMP:

    Timestamp received dgram traffic

  • SO_SNDBUF:

    Send buffer size

  • SO_RCVBUF:

    Receive buffer size

  • SO_SNDLOWAT:

    Send low-water mark

  • SO_RCVLOWAT:

    Receive low-water mark

  • SO_SNDTIMEO:

    Send timeout

  • SO_RCVTIMEO:

    Receive timeout

  • SO_ERROR:

    Get error status and clear

  • SO_TYPE:

    Get socket type

  • SOL_SOCKET:

    Options for socket level

  • AF_UNSPEC:

    Unspecified

  • AF_UNIX:

    Local to host (pipes)

  • AF_LOCAL:

    Backward compatibility with AF_UNIX

  • AF_INET:

    Internetwork: UDP, TCP, etc.

  • AF_IMPLINK:

    Arpanet imp addresses

  • AF_PUP:

    PUP protocols: e.g. BSP

  • AF_CHAOS:

    MIT CHAOS protocols

  • AF_NS:

    XEROX NS protocols

  • AF_ISO:

    ISO protocols

  • AF_OSI:

    ISO protocols (same as AF_ISO)

  • AF_ECMA:

    European computer manufacturers

  • AF_DATAKIT:

    Datakit protocols

  • AF_CCITT:

    CCITT protocols, X.25 etc

  • AF_SNA:

    IBM SNA

  • AF_DECnet:

    DECnet

  • AF_DLI:

    DEC Direct data link interface

  • AF_LAT:

    LAT

  • AF_HYLINK:

    NSC Hyperchannel

  • AF_APPLETALK:

    Apple Talk

  • AF_INET6:

    IPv6

  • IPPROTO_IP:

    IPPROTO_IP

  • IPPROTO_ICMP:

    IPPROTO_ICMP

  • IPPROTO_IGMP:

    IPPROTO_IGMP

  • IPPROTO_IPIP:

    IPPROTO_IPIP

  • IPPROTO_TCP:

    IPPROTO_TCP

  • IPPROTO_EGP:

    IPPROTO_EGP

  • IPPROTO_PUP:

    IPPROTO_PUP

  • IPPROTO_UDP:

    IPPROTO_UDP

  • IPPROTO_IDP:

    IPPROTO_IDP

  • IPPROTO_TP:

    IPPROTO_TP

  • IPPROTO_DCCP:

    IPPROTO_DCCP

  • IPPROTO_IPV6:

    IPPROTO_IPV6

  • IPPROTO_RSVP:

    IPPROTO_RSVP

  • IPPROTO_GRE:

    IPPROTO_GRE

  • IPPROTO_ESP:

    IPPROTO_ESP

  • IPPROTO_AH:

    IPPROTO_AH

  • IPPROTO_MTP:

    IPPROTO_MTP

  • IPPROTO_BEETPH:

    IPPROTO_BEETPH

  • IPPROTO_ENCAP:

    IPPROTO_ENCAP

  • IPPROTO_PIM:

    IPPROTO_PIM

  • IPPROTO_COMP:

    IPPROTO_COMP

  • IPPROTO_SCTP:

    IPPROTO_SCTP

  • IPPROTO_UDPLITE:

    IPPROTO_UDPLITE

  • IPPROTO_MPLS:

    IPPROTO_MPLS

  • IPPROTO_RAW:

    IPPROTO_RAW

  • IPPROTO_MAX:

    IPPROTO_MAX

  • SHUT_RD:

    Shut down the reading side

  • SHUT_WR:

    Shut down the writing side

  • SHUT_RDWR:

    Shut down both sides

  • SOMAXCONN:

    Maximum queue length specifiable by listen.

  • IP_ANYstring:

    The non-designated address used to represent "no particular address" (also referred to as "any address")

  • IP_LOCALstring:

    The loopback address (also known as localhost).

Functions

get_address_info(address, type, family)

Returns ip and name information of a given address.

Parameters
  • number address
  • string? type: : Default value is http
  • int? family: : Default value is [AF_INET]
Returns
  • dictionary

socket(family, type, protocol) ⇢ Exported

Returns a new instance of a Socket.

Parameters
  • number family
  • number? type
  • number? protocol
Returns
  • Socket

Classes

class SocketException < Exception

The SocketException class is the general Exception type thrown from sockets

class Socket

The Socket class provides interface for working with Socket clients and servers.

Properties

  • @printable

Fields

  • hoststring:

    This property holds the host bound, to be bound to or connected to by the current socket. Whenever a host is not given, the host will default to localhost.

  • portint:

    The port currently bound or connected to by the socket.

  • familyint:

    The socket family (which must be one of the AF_ variables). The default family for the socket is AF_INET.

  • typeint:

    The type of socket stream used by the socket. The default socket type is SOCK_STREAM.

  • protocolint:

    The current operating protocol of the socket that controls the underlying behavior of the socket. The default is IPPROTO_TCP.

  • idint:

    The file descriptor id of the current socket on the host machine.

  • is_clientbool:

    true when the socket is a client to a server socket, false otherwise.

  • is_boundbool:

    true when the socket is bound to a given port on the device, false otherwise.

  • is_connectedbool:

    true when the socket is connected to a server socket, false otherwise.

  • is_listeningbool:

    true when the socket is currently listening on a host device port as a server, false otherwise.

  • is_closedbool:

    true when the socket is closed, false otherwise.

  • is_shutdownbool:

    true when the socket is shutdown, false otherwise.

  • is_blockingbool:

    true when the socket is running in a blocking mode, false otherwise.

  • shutdown_reasonint:

    The property holds the reason for which the last shutdown operation was called or -1 if shutdown was never requested.

  • send_timeoutint:

    The amount of time in milliseconds that the socket waits before it terminates a send operation. This is equal to the SO_SNDTIMEO.

  • receive_timeoutint:

    The amount of time in milliseconds that the socket waits before it terminates a receive operation. This is equal to the SO_RCVTIMEO.

Methods

Socket(family, type, protocol, id) ⇢ Constructor

Parameters
  • number family
  • number? type
  • number? protocol

connect(host, port, timeout)

Initiates a connection to the given host on the specified port. If host is nil, it will connect on to the current hostn specified on the socket.

Parameters
  • string host
  • int port
  • int? timeout: : Defaults to 300,000ms (i.e. 300 seconds)
Returns
  • bool

bind(port, host)

Binds this socket to the given port on the given host. If host is nil or not specified, it will connect on to the current hostn specified on the socket.

Parameters
  • int port
  • string? host
Returns
  • bool

send(message, flags)

Sends the specified message to the socket. When this methods accepts a file as a message, the file is read and the resultant bytes of the file content is streamed to the socket.

Parameters
  • string|file|bytes|? message
  • int? flags: : Not currently used.
Returns
  • number greater than -1 if successful indicating the total number of bytes sent or -1 if it fails.

receive(length, flags)

Receives bytes of the given length from the socket. If the length is not given, it default length of -1 indicating that the total available data on the socket stream will be read. If no data is available for read on the socket, the socket will wait to receive data or until the receive_timeout which is also equal to the SO_RCVTIMEO setting of the socket has elapsed before or until it has received the total number of bytes required (whichever comes first).

Parameters
  • int? length
  • int? flags: : Not currently used.
Returns
  • string

read(length)

Reads bytes of the given length from the socket. If the length is not given, it default length of -1 indicating that the total available data on the socket stream will be read.

This method differs from receive() in that it does not check for a socket having data to read or not and will block until data of length have been read or no more data is available for reading.

Parameters
  • int? length: : Default value is 1024
Returns
  • string
Notes
  • Only use this function after a call to receive() has succeeded.

listen(queue_length)

Listen for connections on a socket

This method puts the socket in a state where it is willing to accept incoming connections and creates a queue limit of queue_length for incoming connections. If a connection request arrives with the queue full, the client may receive an error with an indication of ECONNREFUSED. Alternatively, if the underlying protocol supports retransmission, the request may be ignored so that retries may succeed.

When the queue_length is ommited or set to -1, the method will use the default queue limit of the current platform which is usually equal to SOMAXCONN.

Parameters
  • int? queue_length
Returns
  • bool
Notes
  • listen() call applies only to sockets of type SOCK_STREAM (which is the default)

accept()

Accepts a connection on a socket

This method extracts the first connection request on the queue of pending connections, creates a new socket with the same properties of the current socket, and allocates a new file descriptor for the socket. If no pending connections are present on the queue, and the socket is not marked as non-blocking, accept() blocks the caller until a connection is present. If the socket is marked non-blocking and no pending connections are present on the queue, accept() returns an error as described below.

The accepted socket may not be used to accept more connections. The original socket remains open.

Returns
  • Socket

close()

Closes the socket.

Returns
  • bool

shutdown(how)

The shutdown() call causes all or part of a full-duplex connection on the socket associated with socket to be shut down. If how is SHUT_RD, further receives will be disallowed. If how is SHUT_WR, further sends will be disallowed. If how is SHUT_RDWR, further sends and receives will be disallowed.

When how is not specified, it defaults to SHUT_RD.

Parameters
  • int? how
Returns
  • bool

set_option(option, value)

Sets the options of the current socket.

Parameters
  • int option
  • any value
Returns
  • bool
Notes
  • Only SO_ variables are valid option types.

get_option(option)

Gets the options set on the current socket

Parameters
  • int option
Returns
  • any

set_blocking(mode)

Sets if the socket should operate in blocking or non-blocking mode. true for blocking (default) and false for non-blocking.

Parameters
  • bool mode

info()

Returns a dictionary containing the address, ipv6, port and family of the current socket or an empty dictionary if the socket information could not be retrieved.

Returns
  • dictionary