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
    • 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 either the Write() action or WriteMsg() method.
  • 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 MULTICONNECT 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. As there is a limit to the number of connections that can be queued, you can adjust the backlog by writing this field. The default setting is 10 connections.

If the backlog is exceeded, subsequent connections to the socket will typically be met with 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 that can be connected to a server socket.
  Clientsstruct NetClient *For 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.

Refer to a custom function in this field and it will be called whenever the State of the socket (such as connection or disconnection) changes.

The function must be in the format Function(*NetSocket, *ClientSocket, LONG State)

The NetSocket parameter will refer to the NetSocket object to which the Feedback function is subscribed. The reflects the new value in the State field.

  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::SYNCHRONOUSUse synchronous (blocking) network calls.
  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 must follow this definition: ERR Incoming(*NetSocket, OBJECTPTR Context)

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

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

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.
  SocketHandleAPTRPlatform specific reference to the network socket handle.
  StateNTCThe current connection state of the netsocket object.
NameDescription
NTC::CONNECTEDThere is an active connection at present.
NTC::CONNECTINGA connection is being established.
NTC::CONNECTING_SSLAn SSL connection is being established.
NTC::DISCONNECTEDThere is no connection.
  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, struct NetClient * 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)
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.

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)
ReadMsgRead a message from the socket.
ERR ns::ReadMsg(OBJECTPTR Object, APTR * Message, INT * Length, INT * Progress, INT * CRC)
ParameterDescription
MessageA pointer to the message buffer will be placed here if a message has been received.
LengthThe length of the message is returned here.
ProgressThe number of bytes that have been read for the incoming message.
CRCIndicates the CRC value that the message is expected to match.

This method reads messages that have been sent to the socket using Parasol Message Protocols. Any message sent with the WriteMsg() method will conform to this protocol, thus simplifying message transfers between programs based on the core platform at either point of the network link.

This method never returns a successful error code unless an entire message has been received from the sender.

Error Codes
OkayA complete message has been read and indicated in the result parameters.
BadDataThe message header or tail was invalid, or the message length exceeded internally imposed limits.
LimitedSuccessSome data has arrived, but the entire message is incomplete. The length of the incoming message may be indicated in the Length parameter.
ArgsInvalid arguments passed to function.
NoDataNo new data was found for the socket.
AllocMemoryA message buffer could not be allocated.
NullArgsFunction call missing argument value(s)
WriteMsgWrites a message to the socket.
ERR ns::WriteMsg(OBJECTPTR Object, APTR Message, INT Length)
ParameterDescription
MessagePointer to the message to send.
LengthThe length of the message.

Messages can be written to sockets with the WriteMsg method and read back by the receiver with ReadMsg(). The message data is sent through the Write() action, so the standard process will apply (the message will be queued and does not block if buffers are full).

Error Codes
OkayOperation successful.
ArgsInvalid arguments passed to function.
OutOfRangeA specified number is outside of the valid range.
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::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::CONNECTING_SSLAn SSL connection is being established.
NTC::DISCONNECTEDThere is no connection.
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

NetClient Structure

Simple data storage class utilised by NetSocket to represent a client machine/IP.

FieldTypeDescription
IPBYTEIP address in 4/8-byte format
Nextstruct NetClient *Next client in the chain
Prevstruct NetClient *Previous client in the chain
NetSocketobjNetSocket *Reference to the parent socket
SocketsobjClientSocket *Pointer to a list of sockets opened with this client.
ClientDataAPTRFree for user data storage.
TotalSocketsINTCount of all created sockets
NetSocket class documentation © Paul Manias © 2005-2025