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

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::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::SSL_NO_VERIFYDisable SSL certificate verification (for testing only).
NSF::SYNCHRONOUSUse synchronous (blocking) network calls.
  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.

  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.

  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. The function must be in the format ERR Outgoing(*NetSocket, OBJECTPTR Context)

The NetSocket parameter refers to the NetSocket object. The Context refers to the object that set the Outgoing field.

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

The Outgoing field is ineffective if the NetSocket is in server mode (target a connected client socket instead).

  PortINTThe port number to use for initiating a connection.
  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.
  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.

  ValidCertINTIndicates certificate validity if the socket is encrypted with a certificate.

After an encrypted connection has been made to a server, the ValidCert field can be used to determine the validity of the server's certificate.

If encrypted communication is not supported, ERR::NoSupport is returned. If the certificate is valid or the connection is not encrypted, a value of zero is returned to indicate that the connection is valid.

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.

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

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.
InvalidStateThe NetSocket was not in the state NTC::DISCONNECTED.
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)
NetSocket class documentation © Paul Manias © 2005-2025

NSF Type

NameDescription
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::SSL_NO_VERIFYDisable SSL certificate verification (for testing only).
NSF::SYNCHRONOUSUse synchronous (blocking) network calls.
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.
NetSocket module documentation © Paul Manias © 2005-2025

IPAddress Structure

FieldTypeDescription
DataINT128-bit array for supporting both V4 and V6 IP addresses.
TypeIPADDRIdentifies the address Data value as a V4 or V6 address type.
PadINTUnused padding for 64-bit alignment
NetSocket class documentation © Paul Manias © 2005-2025