Link Search Menu Expand Document

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


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_ANY
The non-designated address used to represent “no particular address” (also referred to as “any address”)
socket.IP_LOCAL
The loopback address (also known as localhost)

Functions


socket.get_address_info(address: number [, type: string [, family: int]])
returns ip and name information of a given address
return dictionary

Classes


class SocketException < Exception


The SocketException class is the general Exception type thrown from sockets

class SocketException methods


SocketException(message: string)
constructor

class Socket


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

class Socket properties


Socket.host
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.
Socket.port
The port currently bound or connected to by the socket
Socket.family
The socket family (which must be one of the AF_ variables). The default family for the socket is AF_INET
Socket.type
The type of socket stream used by the socket. The default socket type is SOCK_STREAM
Socket.protocol
The current operating protocol of the socket that controls the underlying behavior of the socket. The default is IPPROTO_TCP.
Socket.id
The file descriptor id of the current socket on the host machine.
Socket.is_client
true when the socket is a client to a server socket, false otherwise.
Socket.is_bound
true when the socket is bound to a given port on the device, false otherwise.
Socket.is_connected
true when the socket is connected to a server socket, false otherwise.
Socket.is_listening
true when the socket is currently listening on a host device port as a server, false otherwise.
Socket.is_closed
true when the socket is closed, false otherwise.
Socket.is_shutdown
true when the socket is shutdown, false otherwise.
Socket.is_blocking
true when the socket is running in a blocking mode, false otherwise.
Socket.shutdown_reason
The property holds the reason for which the last shutdown operation was called or -1 if shutdown was never requested.
Socket.send_timeout
The amount of time in milliseconds that the socket waits before it terminates a send operation. This is equal to the SO_SNDTIMEO.
Socket.receive_timeout
The amount of time in milliseconds that the socket waits before it terminates a receive operation. This is equal to the SO_RCVTIMEO.

class Socket methods


Socket(family: number [, type: number [, protocol: number]])
example Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
constructor
connect(host: string, port: int [, timeout: int])
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.
default timeout = 300,000ms (i.e. 300 seconds)
return bool
bind(port: int [, host: string])
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.
return bool
send(message: string | file | bytes, flags: int)
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.
  • the flags parameter is currently redundant and is kept only to remanin compatible with future plans for this method.
return number greater than -1 if successful indicating the total number of bytes sent or -1 if it fails.
receive([length: int [, flags: int]])
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).
  • the flags parameter is currently redundant and is kept only to remanin compatible with future plans for this method.
return string
read([length: int])
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.

  • Only use this function after a call to receive() has succeeded.
default Length = 1024
return string
listen([queue_length: int])
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.

  • listen() call applies only to sockets of type SOCK_STREAM (which is the default)
return 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 socket, remains open.

return Socket
close()
Closes the socket
return bool
shutdown([how: int])
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.

return bool
set_option(option: int, value: any)
Sets the options of the current socket.
  • Only SO_ variables are valid option types
return bool
get_option(option: int)
Gets the options set on the current socket
return any
set_blocking(mode: bool)
Sets if the socket should operate in blocking or non-blocking mode. true for blocking (default) and false for non-blocking.
info()
Returns a dictionary containing the address, port and family of the current socket or an empty dictionary if the socket information could not be retrieved.
return dictionary

Back to top

Copyright © 2021 Ore Richard Muyiwa. Distributed under the MIT license.