Parasol Framework
  • Gallery
  • API
  • Wiki
  • GitHub
    • Audio
    • Core
    • Display
    • Fluid
    • Font
    • Network
    • Vector
    • Audio
    • Sound
    • File
    • MetaClass
    • Module
    • StorageDevice
    • Task
    • Thread
    • Time
    • Compression
    • Config
    • Script
    • XML
    • Controller
    • BlurFX
    • ColourFX
    • CompositeFX
    • ConvolveFX
    • DisplacementFX
    • FilterEffect
    • FloodFX
    • ImageFX
    • LightingFX
    • MergeFX
    • MorphologyFX
    • OffsetFX
    • RemapFX
    • SourceFX
    • TurbulenceFX
    • WaveFunctionFX
    • Scintilla
    • ScintillaSearch
    • Bitmap
    • Clipboard
    • Display
    • Document
    • Font
    • Picture
    • Pointer
    • Surface
    • SVG
    • ClientSocket
    • HTTP
    • NetClient
    • NetSocket
    • Proxy
    • Vector
    • VectorClip
    • VectorColour
    • VectorEllipse
    • VectorFilter
    • VectorGradient
    • VectorGroup
    • VectorImage
    • VectorPath
    • VectorPattern
    • VectorPolygon
    • VectorRectangle
    • VectorScene
    • VectorShape
    • VectorSpiral
    • VectorText
    • VectorTransition
    • VectorViewport
    • VectorWave

NetSocket Class

Manages network connections via TCP/IP sockets.

The NetSocket class provides a simple way of managing TCP/IP socket communications. Connections from a single client to the server and from the server to multiple clients are supported. SSL functionality is also integrated.

The design of the NetSocket class caters to asynchronous (non-blocking) communication. This is achieved primarily through callback fields - connection alerts are managed by Feedback, incoming data is received through Incoming and readiness for outgoing data is supported by Outgoing.

Client-Server Connections

After a connection has been established, data may be written using any of the following methods:

  • Write directly to the socket with the Write() action.
  • Subscribe to the socket by referring to a routine in the Outgoing field. The routine will be called to initially fill the internal write buffer, thereafter it will be called whenever the buffer is empty.

It is possible to write to a NetSocket object before the connection to a server is established. Doing so will buffer the data in the socket until the connection with the server has been initiated, at which point the data will be immediately sent.

Server-Client Connections

To accept incoming client connections, create a NetSocket object with the SERVER flag set and define the Port value on which to listen for new clients. If multiple connections from a single client IP address are allowed, set the MULTI_CONNECT flag.

When a new connection is detected, the Feedback function will be called as Feedback(*NetSocket, *ClientSocket, NTC State)

The NetSocket parameter refers to the original NetSocket object, ClientSocket applies if a client connection is involved and the State value will be set to NTC::CONNECTED. If a client disconnects, the Feedback function will be called in the same manner but with a State value of NTC::DISCONNECTED.

Information on all active connections can be read from the Clients field. This contains a linked list of IP addresses and their connections to the server port.

To send data to a client, write it to the target ClientSocket.

All data that is received from client sockets will be passed to the Incoming feedback routine with a reference to a ClientSocket.

SSL Server Certificates

For SSL server sockets, custom certificates can be specified using the SSLCertificate field. Both PEM and PKCS#12 formats are supported across all platforms.

Example with PKCS#12 certificate:

netsocket = obj.new('netsocket', { flags = 'SERVER|SSL', port = 8443, sslCertificate = 'config:ssl/server.p12', sslKeyPassword = 'password123' })

Example with PEM certificate and separate private key:

netsocket = obj.new('netsocket', { flags = 'SERVER|SSL', port = 8443, sslCertificate = 'config:ssl/server.crt', sslPrivateKey = 'config:ssl/server.key' })

If no custom certificate is specified, the framework will automatically use a localhost self-signed certificate for development purposes. For production use, always specify a proper certificate signed by a trusted CA.

Structure

The NetSocket class consists of the following fields:

Access
NameTypeComment
  AddressSTRINGAn IP address or domain name to connect to.

If this field is set with an IP address or domain name prior to initialisation, an attempt to connect to that location will be made when the NetSocket is initialised. Post-initialisation this field cannot be set by the client, however calls to Connect() will result in it being updated so that it always reflects the named address of the current connection.

  BacklogINTThe maximum number of connections that can be queued against the socket.

Incoming connections to NetSocket objects are queued until they are answered by the object. Setting the Backlog adjusts the maximum number of connections on the queue, which otherwise defaults to 10.

If the backlog is exceeded, subsequent connections to the socket should expect a connection refused error.

  ClientDataAPTRA client-defined value that can be useful in action notify events.

This is a free-entry field value that can store client data for future reference.

  ClientLimitINTThe maximum number of clients (unique IP addresses) that can be connected to a server socket.

The ClientLimit value limits the maximum number of IP addresses that can be connected to the socket at any one time. For socket limits per client, see the SocketLimit field.

  Clients*NetClientFor server sockets, lists all clients connected to the server.
  ErrorERRInformation about the last error that occurred during a NetSocket operation

This field describes the last error that occurred during a NetSocket operation:

In the case where a NetSocket object enters the NTC::DISCONNECTED state from the NTC::CONNECTED state, this field can be used to determine how a TCP connection was closed.

NameDescription
ERR::OkayThe connection was closed gracefully. All data sent by the peer has been received.
ERR::DisconnectedThe connection was broken in a non-graceful fashion. Data may be lost.
ERR::TimeOutThe connect operation timed out.
ERR::ConnectionRefusedThe connection was refused by the remote host. Note: This error will not occur on Windows, and instead the Error field will be set to ERR::Failed.
ERR::NetworkUnreachableThe network was unreachable. Note: This error will not occur on Windows, and instead the Error field will be set to ERR::Failed.
ERR::HostUnreachableNo path to host was found. Note: This error will not occur on Windows, and instead the Error field will be set to ERR::Failed.
ERR::FailedAn unspecified error occurred.
  FeedbackFUNCTIONA callback trigger for when the state of the NetSocket is changed.

The client can define a function in this field to receive notifications whenever the state of the socket changes - typically connection messages.

In server mode, the function must follow the prototype Function(*NetSocket, *ClientSocket, NTC State). Otherwise Function(*NetSocket, NTC State).

The NetSocket parameter refers to the NetSocket object to which the function is subscribed. In server mode, ClientSocket refers to the ClientSocket on which the state has changed.

  FlagsNSFOptional flags.
NameDescription
NSF::BROADCASTEnable broadcast (UDP only).
NSF::DISABLE_SERVER_VERIFYDisable SSL certificate verification (for testing only).
NSF::LOG_ALLPrint extra log messages.
NSF::MULTI_CONNECTAllow multiple connections from the same IP when in server mode.
NSF::SERVERPuts the socket into server mode. In this state the netsocket object will wait for incoming connections from clients.
NSF::SSLUse Secure Sockets Layer for all communication.
NSF::SYNCHRONOUSUse synchronous (blocking) network calls.
NSF::UDPUse UDP (connectionless datagram protocol) instead of TCP.
  HandleAPTRPlatform specific reference to the network socket handle.
  IncomingFUNCTIONCallback that is triggered when the socket receives data.

The Incoming field can be set with a custom function that will be called whenever the socket receives data. The function prototype for C++ is ERR Incoming(*NetSocket, APTR Meta). For Fluid use function Incoming(NetSocket).

The NetSocket parameter refers to the NetSocket object. Meta is optional userdata from the FUNCTION.

Retrieve data from the socket with the Read() action. Reading at least some of the data from the socket is compulsory - if the function does not do this then the data will be cleared from the socket when the function returns. If the callback function returns/raises ERR::Terminate then the Incoming field will be cleared and the function will no longer be called. All other error codes are ignored.

  MaxPacketSizeINTMaximum UDP packet size for sending and receiving data.

This field sets the maximum size in bytes for UDP packets when sending or receiving data. It only applies to UDP sockets and is ignored for TCP connections. The default value is 65507 bytes, which is the maximum payload size for UDP packets (65535 - 8 bytes UDP header - 20 bytes IP header).

If you attempt to send a packet larger than MaxPacketSize, a warning will be logged and the operation may fail. When receiving data, packets larger than this size will be truncated.

  MsgLimitINTLimits the size of incoming and outgoing data packets.

This field limits the size of incoming and outgoing message queues (each socket connection receives two queues assigned to both incoming and outgoing messages). The size is defined in bytes. Sending or receiving messages that overflow the queue results in the connection being terminated with an error.

The default setting is 1 megabyte.

  MulticastTTLINTTime-to-live (hop limit) for multicast packets.

This field sets the time-to-live (TTL) value for multicast packets sent from UDP sockets. The TTL determines how many network hops (routers) a multicast packet can traverse before being discarded. This helps prevent multicast traffic from flooding the network indefinitely.

The default TTL is 1, which restricts multicast to the local network segment. Higher values allow multicast packets to traverse more network boundaries:

  • 1: Local network segment only
  • 32: Within the local site
  • 64: Within the local region
  • 128: Within the local continent
  • 255: Unrestricted (global)
  OutQueueSizeINTThe number of bytes on the socket's outgoing queue.
  OutgoingFUNCTIONCallback that is triggered when a socket is ready to send data.

The Outgoing field can be set with a custom function that will be called whenever the socket is ready to send data. In client mode the function must be in the format ERR Outgoing(*NetSocket, APTR Meta). In server mode the function format is ERR Outgoing(*NetSocket, *ClientSocket, APTR Meta).

To send data to the NetSocket object, call the Write() action. If the callback function returns an error other than ERR::Okay then the Outgoing field will be cleared and the function will no longer be called.

  PortINTThe port number to use for connections.
  SSLCertificateSTRINGSSL certificate file to use if in server mode.

Set SSLCertificate to the path of an SSL certificate file to use when the NetSocket is in server mode. The certificate file must be in a supported format such as PEM, CRT, or P12. If no certificate is defined, the NetSocket will either self-sign or use a localhost certificate, if available.

  SSLKeyPasswordSTRINGSSL private key password.

If the SSL private key is encrypted, set this field to the password required to decrypt it. If the private key is not encrypted, this field can be left empty.

  SocketLimitINTLimits the number of connected sockets per client IP address.
  StateNTCThe current connection state of the NetSocket object.

The State reflects the connection state of the NetSocket. If the Feedback field is defined with a function, it will be called automatically whenever the state is changed. Note that the ClientSocket parameter will be NULL when the Feedback function is called.

Note that in server mode this State value should not be used as it cannot reflect the state of all connected client sockets. Each ClientSocket carries its own independent State value for use instead.

NameDescription
NTC::CONNECTEDThere is an active connection at present.
NTC::CONNECTINGA connection is being established.
NTC::DISCONNECTEDThere is no connection.
NTC::HANDSHAKINGAn SSL connection is being established.
NTC::MULTISTATEIn server mode the NetSocket will be set to MULTISTATE to indicate one or more client connections.
NTC::RESOLVINGThe host name is being resolved.
  TotalClientsINTIndicates the total number of clients currently connected to the socket (if in server mode).

In server mode, the NetSocket will maintain a count of the total number of clients currently connected to the socket. You can read the total number of connections from this field.

In client mode, this field is always set to zero.

Actions

The following actions are currently supported:

DisableDisables sending and receiving on the socket.
ERR acDisable(*Object)

This method will stop all sending and receiving of data over the socket. This is irreversible.

Error Codes
OkayOperation successful.
FailedShutdown operation failed.
ReadRead information from the socket.
ERR acRead(*Object, APTR Buffer, INT Length, INT *Result)
ParameterDescription
BufferPoints a buffer that will receive the data.
LengthThe total number of bytes to read from the object. This value cannot exceed the size of the Buffer.
ResultThe Read action will write this parameter with the total number of bytes read into the Buffer.

The Read() action will read incoming data from the socket and write it to the provided buffer. If the socket connection is safe, success will always be returned by this action regardless of whether or not data was available. Almost all other return codes indicate permanent failure and the socket connection will be closed when the action returns.

Because NetSocket objects are non-blocking, reading from the socket is normally performed in the Incoming callback. Reading from the socket when no data is available will result in an immediate return with no output.

Error Codes
OkayRead successful (if no data was on the socket, success is still indicated).
FailedA permanent failure has occurred and socket has been closed.
InvalidStateThe socket is not in a state that allows reading (e.g. during SSL handshake).
DisconnectedThe socket connection is closed.
NullArgsFunction call missing argument value(s)
WriteWrites data to the socket.
ERR acWrite(*Object, APTR Buffer, INT Length, INT Result)
ParameterDescription
BufferA buffer containing the data that will be written to the object.
LengthThe total number of bytes to write to the object.
ResultThis parameter with be updated with the total number of bytes written from the Buffer.

Writing data to a socket will send raw data to the remote client or server. Write connections are buffered, so any data overflow generated in a call to this action will be buffered into a software queue. Resource limits placed on the software queue are governed by the MsgLimit field setting.

Do not use this action if in server mode. Instead, write to the ClientSocket object that will receive the data.

It is possible to write to a socket in advance of any connection being made. The netsocket will queue the data and automatically send it once the first connection has been made.

Methods

The following methods are currently supported:

ConnectConnects a NetSocket to an address.
ERR ns::Connect(OBJECTPTR Object, CSTRING Address, INT Port, DOUBLE Timeout)
ParameterDescription
AddressString containing either a domain name (e.g. www.google.com) or an IP address (e.g. 123.123.123.123)
PortRemote port to connect to.
TimeoutConnection timeout in seconds (0 = no timeout).

This method initiates the connection process with a target IP address. The address to connect to can be specified either as a domain name, in which case the domain name is first resolved to an IP address, or the address can be specified in standard IP notation.

This method is non-blocking. It will return immediately and the connection will be resolved once the server responds to the connection request or an error occurs. Client code should subscribe to the State field to respond to changes to the connection state.

Pre-Condition: Must be in a connection state of NTC::DISCONNECTED

Post-Condition: If this method returns ERR::Okay, will be in state NTC::CONNECTING.

Error Codes
OkayThe NetSocket connecting process was successfully started.
FailedThe connect failed for some other reason.
ArgsAddress was NULL, or Port was not in the required range.
TimeOutConnection attempt timed out.
InvalidStateThe NetSocket was not in the state NTC::DISCONNECTED or the object is in server mode.
HostNotFoundHost name resolution failed.
DisconnectClientDisconnects all sockets connected to a specific client IP.
ERR ns::DisconnectClient(OBJECTPTR Object, objNetClient * Client)
ParameterDescription
ClientThe client to be disconnected.

For server sockets with client IP connections, this method will terminate all socket connections made to a specific client IP and free the resources allocated to it. If Feedback is defined, a DISCONNECTED state message will also be issued for each socket connection.

If only one socket connection needs to be disconnected, please use DisconnectSocket().

Error Codes
OkayOperation successful.
NullArgsFunction call missing argument value(s)
WrongClassThe Client object is not of type NetClient.
DisconnectSocketDisconnects a single socket that is connected to a client IP address.
ERR ns::DisconnectSocket(OBJECTPTR Object, objClientSocket * Socket)
ParameterDescription
SocketThe client socket to be disconnected.

This method will disconnect a socket connection for a given client. If Feedback is defined, a DISCONNECTED state message will also be issued.

NOTE: To terminate the connection of a socket acting as the client, either free the object or return/raise ERR::Terminate during Incoming feedback.

Error Codes
OkayOperation successful.
NullArgsFunction call missing argument value(s)
GetLocalIPAddressReturns the IP address that the socket is locally bound to.
ERR ns::GetLocalIPAddress(OBJECTPTR Object, struct IPAddress * Address)
ParameterDescription
AddressPointer to an IPAddress structure which will be set to the result of the query if successful.

This method performs the POSIX equivalent of getsockname(). It returns the current address to which the NetSocket is bound.

Error Codes
OkayOperation successful.
FailedGeneral failure.
NullArgsFunction call missing argument value(s)
JoinMulticastGroupJoin a multicast group for receiving multicast packets (UDP only).
ERR ns::JoinMulticastGroup(OBJECTPTR Object, CSTRING Group)
ParameterDescription
GroupThe multicast group address to join (e.g. 224.1.1.1).

This method joins a multicast group, allowing the socket to receive packets sent to the specified multicast address. This is only available for UDP sockets.

The socket must be bound to a local address before joining a multicast group.

Error Codes
OkaySuccessfully joined the multicast group.
FailedFailed to join multicast group.
ArgsInvalid multicast address.
NoSupportSocket is not configured for UDP mode.
LeaveMulticastGroupLeave a multicast group (UDP only).
ERR ns::LeaveMulticastGroup(OBJECTPTR Object, CSTRING Group)
ParameterDescription
GroupThe multicast group address to leave.

This method leaves a previously joined multicast group, stopping the reception of packets sent to the specified multicast address.

Error Codes
OkaySuccessfully left the multicast group.
FailedFailed to leave multicast group.
ArgsInvalid multicast address.
NoSupportSocket is not configured for UDP mode.
RecvFromReceive a datagram packet from any address (UDP only).
ERR ns::RecvFrom(OBJECTPTR Object, struct IPAddress * Source, APTR Buffer, INT BufferSize, INT * BytesRead)
ParameterDescription
SourceSource IP address of the received packet.
BufferPointer to the buffer where received data will be stored.
BufferSizeSize of the receive buffer in bytes.
BytesReadNumber of bytes actually received.

This method receives a datagram packet from any source address. It is only available for sockets configured with the UDP flag. Unlike TCP connections, UDP is connectionless so packets can be received from any source without establishing a connection first.

The method is non-blocking and will return immediately. If no data is available, ERR::Okay will be returned with BytesRead set to zero.

The source address and port of the received packet will be provided in the output parameters.

For TCP sockets, use the standard Read action instead.

Error Codes
OkayData was received successfully, or no data available.
ArgsInvalid arguments provided.
NoSupportSocket is not configured for UDP mode.
BufferOverflowReceive buffer is too small for the incoming packet.
SendToSend a datagram packet to a specific address (UDP only).
ERR ns::SendTo(OBJECTPTR Object, struct IPAddress * Dest, APTR Data, INT Length, INT * BytesSent)
ParameterDescription
DestThe destination IP address (IPv4 or IPv6) and port number.
DataPointer to the data buffer to send.
LengthNumber of bytes to send from Data.
BytesSentNumber of bytes actually sent.

This method sends a datagram packet to a specified IP address and port. It is only available for sockets configured with the UDP flag. Unlike TCP connections, UDP is connectionless so packets can be sent to any address without establishing a connection first.

The method is non-blocking and will return immediately. If the network buffer is full, an ERR::BufferOverflow error will be returned and the client should retry the operation later.

For TCP sockets, use the standard Write action instead.

Error Codes
OkayThe packet was sent successfully.
OutOfRangeInvalid port number specified.
BufferOverflowThe network buffer is full, retry later.
InvalidStateSocket is not configured for UDP mode.
NetworkUnreachableThe destination network is unreachable.
NullArgsInvalid arguments provided.
NetSocket class documentation © Paul Manias © 2005-2025

NSF Type

NameDescription
NSF::BROADCASTEnable broadcast (UDP only).
NSF::DISABLE_SERVER_VERIFYDisable SSL certificate verification (for testing only).
NSF::LOG_ALLPrint extra log messages.
NSF::MULTI_CONNECTAllow multiple connections from the same IP when in server mode.
NSF::SERVERPuts the socket into server mode. In this state the netsocket object will wait for incoming connections from clients.
NSF::SSLUse Secure Sockets Layer for all communication.
NSF::SYNCHRONOUSUse synchronous (blocking) network calls.
NSF::UDPUse UDP (connectionless datagram protocol) instead of TCP.
NetSocket module documentation © Paul Manias © 2005-2025

NTC Type

NetSocket states

NameDescription
NTC::CONNECTEDThere is an active connection at present.
NTC::CONNECTINGA connection is being established.
NTC::DISCONNECTEDThere is no connection.
NTC::HANDSHAKINGAn SSL connection is being established.
NTC::MULTISTATEIn server mode the NetSocket will be set to MULTISTATE to indicate one or more client connections.
NTC::RESOLVINGThe host name is being resolved.
NetSocket module documentation © Paul Manias © 2005-2025

IPAddress Structure

FieldTypeDescription
DataINT128-bit array for supporting both V4 (32-bit host order) and V6 (8-bit byte order) IP addresses.
TypeIPADDRIdentifies the address Data value as a V4 or V6 address type.
PortINTFor UDP packets, identifies the client port number in host byte order.
NetSocket class documentation © Paul Manias © 2005-2025