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 bidirectional 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 instantiated 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 actually 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()

Fields

socket.SOCK_STREAM
stream socket
socket.SOCK_DGRAM
datagram socket
socket.SOCK_RAW
raw-protocol interface
socket.SOCK_RDM
reliably-delivered message
socket.SOCK_SEQPACKET
sequenced packet stream
socket.SO_DEBUG
Turn on debugging info recording
socket.SO_ACCEPTCONN
Socket has had listen()
socket.SO_REUSEADDR
Allow local address reuse
socket.SO_KEEPALIVE
Keep connections alive
socket.SO_DONTROUTE
Just use interface addresses
socket.SO_BROADCAST
Permit sending of broadcast msgs
socket.SO_USELOOPBACK
Bypass hardware when possible
socket.SO_LINGER
Linger on close if data present (in ticks)
socket.SO_OOBINLINE
Leave received OOB data in line
socket.SO_REUSEPORT
Allow local address & port reuse
socket.SO_TIMESTAMP
Timestamp received dgram traffic
socket.SO_SNDBUF
Send buffer size
socket.SO_RCVBUF
Receive buffer size
socket.SO_SNDLOWAT
Send low-water mark
socket.SO_RCVLOWAT
Receive low-water mark
socket.SO_SNDTIMEO
Send timeout
socket.SO_RCVTIMEO
Receive timeout
socket.SO_ERROR
Get error status and clear
socket.SO_TYPE
Get socket type
socket.SOL_SOCKET
Options for socket level
socket.AF_UNSPEC
Unspecified
socket.AF_UNIX
Local to host (pipes)
socket.AF_LOCAL
Backward compatibility with AF_UNIX
socket.AF_INET
Internetwork: UDP, TCP, etc.
Arpanet imp addresses
socket.AF_PUP
PUP protocols: e.g. BSP
socket.AF_CHAOS
MIT CHAOS protocols
socket.AF_NS
XEROX NS protocols
socket.AF_ISO
ISO protocols
socket.AF_OSI
ISO protocols (same as AF_ISO)
socket.AF_ECMA
European computer manufacturers
socket.AF_DATAKIT
Datakit protocols
socket.AF_CCITT
CCITT protocols, X.25 etc
socket.AF_SNA
IBM SNA
socket.AF_DECnet
DECnet
socket.AF_DLI
DEC Direct data link interface
socket.AF_LAT
LAT
NSC Hyperchannel
socket.AF_APPLETALK
Apple Talk
socket.AF_INET6
IPv6
socket.IPPROTO_IP
IPPROTO_IP
socket.IPPROTO_ICMP
IPPROTO_ICMP
socket.IPPROTO_IGMP
IPPROTO_IGMP
socket.IPPROTO_IPIP
IPPROTO_IPIP
socket.IPPROTO_TCP
IPPROTO_TCP
socket.IPPROTO_EGP
IPPROTO_EGP
socket.IPPROTO_PUP
IPPROTO_PUP
socket.IPPROTO_UDP
IPPROTO_UDP
socket.IPPROTO_IDP
IPPROTO_IDP
socket.IPPROTO_TP
IPPROTO_TP
socket.IPPROTO_DCCP
IPPROTO_DCCP
socket.IPPROTO_IPV6
IPPROTO_IPV6
socket.IPPROTO_RSVP
IPPROTO_RSVP
socket.IPPROTO_GRE
IPPROTO_GRE
socket.IPPROTO_ESP
IPPROTO_ESP
socket.IPPROTO_AH
IPPROTO_AH
socket.IPPROTO_MTP
IPPROTO_MTP
socket.IPPROTO_BEETPH
IPPROTO_BEETPH
socket.IPPROTO_ENCAP
IPPROTO_ENCAP
socket.IPPROTO_PIM
IPPROTO_PIM
socket.IPPROTO_COMP
IPPROTO_COMP
socket.IPPROTO_SCTP
IPPROTO_SCTP
socket.IPPROTO_UDPLITE
IPPROTO_UDPLITE
socket.IPPROTO_MPLS
IPPROTO_MPLS
socket.IPPROTO_RAW
IPPROTO_RAW
socket.IPPROTO_MAX
IPPROTO_MAX
socket.SHUT_RD
Shut down the reading side
socket.SHUT_WR
Shut down the writing side
socket.SHUT_RDWR
Shut down both sides
socket.SOMAXCONN
Maximum queue length specifiable by listen.
socket.IP_ANYstring
The non-designated address used to represent "no particular address" (also referred to as "any address")
socket.IP_LOCALstring
The loopback address (also known as localhost).

Functions

socket.get_address_info(address, type, family)

Returns ip and name information of a given address.

  • @params:
    • number address

    • string? type Default value is http

    • int? family Default value is [AF_INET]

  • @returns: dictionary
socket.socket(family, type, protocol) ➝ Exported

Returns a new instance of a Socket.

  • @params:
    • 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.

@printable

.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.

.Socket(family, type, protocol, id) ➝ Constructor

socket.Socket constructor

  • @params:
    • 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.

  • @params:
    • 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.

  • @params:
    • 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.

  • @params:
    • 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).

  • @params:
    • 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.

@notes:

  • Only use this function after a call to receive() has succeeded.
  • @params:
    • int? length Default value is 1024
  • @returns: string
.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 omitted or set to -1, the method will use the default queue limit of the current platform which is usually equal to SOMAXCONN.

@notes:

  • listen() call applies only to sockets of type SOCK_STREAM (which is the default)
  • @params:
    • int? queue_length
  • @returns: bool
.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.

  • @params:
    • int? how
  • @returns: bool
.set_option(option, value)

Sets the options of the current socket.

@notes:

  • Only SO_ variables are valid option types.
  • @params:
    • int option
    • any value
  • @returns: bool
.get_option(option)

Gets the options set on the current socket

  • @params:
    • 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.

  • @params:
    • 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