Kōtuku
  • Gallery
  • API
  • Wiki
  • GitHub
    • Audio
    • Config
    • Core
    • Display
    • Document
    • Font
    • HTTP
    • Network
    • Regex
    • SVG
    • Tiri
    • Vector
    • XML
    • XQuery
    • XRandR
      • Audio
      • MP3
      • Sound
      • File
      • MetaClass
      • Module
      • StorageDevice
      • Task
      • Thread
      • Time
      • Compression
      • CompressedStream
      • Config
      • LZMAStream
      • Script
      • Tiri
      • XML
      • XQuery
      • Controller
      • BlurFX
      • ColourFX
      • CompositeFX
      • ConvolveFX
      • DisplacementFX
      • FilterEffect
      • FloodFX
      • ImageFX
      • LightingFX
      • MergeFX
      • MorphologyFX
      • OffsetFX
      • RemapFX
      • SourceFX
      • TurbulenceFX
      • WaveFunctionFX
      • Scintilla
      • Bitmap
      • Clipboard
      • Display
      • Document
      • Font
      • Image
      • Pointer
      • Surface
      • SVG
      • ClientSocket
      • HTTP
      • NetClient
      • NetLookup
      • NetServer
      • NetSocket
      • Proxy
      • Gradient
      • GradientConic
      • GradientContour
      • GradientDiamond
      • GradientDiffusion
      • GradientDistal
      • GradientGouraud
      • GradientLinear
      • GradientMesh
      • GradientRadial
      • GradientVoronoi
      • Vector
      • VectorClip
      • VectorColour
      • VectorEllipse
      • VectorFilter
      • VectorGradient
      • VectorGroup
      • VectorImage
      • VectorPath
      • VectorPattern
      • VectorPolygon
      • VectorRectangle
      • VectorScene
      • VectorShape
      • VectorSpiral
      • VectorText
      • VectorTransition
      • VectorViewport
      • VectorWave
      • Linux Builds
      • Windows Builds
      • Customising Your Build
      • Kōtuku Objects
      • Kōtuku In Depth
      • Kōtuku Design Patterns
      • Coding With AI
      • Regex Manual
      • XML Comparisons
      • Tiri Reference Manual
      • Config API
      • Defer Syntax
      • GUI API
      • HTTP Server API
      • I/O API
      • JSON API
      • OAuth API
      • Options API
      • Proxy Server API
      • Tempus API
      • URL API
      • VFX API
      • Widgets
      • RIPL Reference Manual
      • Origo
      • Flute / Unit Testing
      • Tuku
      • Embedded Document Format
      • TDL Reference Manual
      • TDL Tools
      • Action Reference Manual
      • System Error Codes

NetSocket Class

Manages network connections via TCP/IP sockets.

The NetSocket class provides a simple way of managing outbound TCP/IP socket communications. It can connect to remote TCP servers, exchange UDP datagrams when the UDP flag is set, and optionally use SSL. Inbound listening and accepted client management are provided by the NetServer subclass, with each accepted TCP connection represented by a ClientSocket.

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.

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

Inbound Listeners

Use NetServer when a program needs to bind a local port and accept inbound clients. NetServer inherits common socket fields from NetSocket, reports client state changes through Feedback with a ClientSocket parameter, and exposes active clients through its Clients field. Data for accepted TCP clients is read from and written to ClientSocket objects.

Structure

The NetSocket class consists of the following fields:

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

For NetSocket clients, 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 object 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.

For NetServer listeners, this inherited field identifies the local address to bind before initialisation. Use localhost, *, an IPv4 address or an IPv6 address.

 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.

 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.

For NetSocket clients, the function must follow the prototype Function(*NetSocket, NTC State). For NetServer listeners, the inherited field uses Function(*NetServer, *ClientSocket, NTC State).

The first parameter refers to the object to which the function is subscribed. For NetServer listeners, ClientSocket refers to the ClientSocket on which the state has changed.

 FlagsNSFOptional flags.
NameDescription
NSF::BROADCASTEnable broadcast (UDP only).
NSF::DISABLE_SERVER_VERIFYDisable SSL server certificate verification for client sockets (testing only).
NSF::KEEP_ALIVEEnable TCP keep-alive probes using operating system defaults.
NSF::LOG_ALLPrint extra log messages.
NSF::MULTI_CONNECTAllow multiple connections from the same IP (NetServer only).
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 Tiri use function Incoming(NetSocket).

The NetSocket parameter refers to the NetSocket object. Meta is optional userdata from the FUNCTION. For NetServer listeners, this inherited field receives Incoming(*NetServer, *ClientSocket, APTR Meta) in C++ or function Incoming(NetServer, ClientSocket) in Tiri, and data must be read from the supplied ClientSocket.

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. For NetSocket clients the function must be in the format ERR Outgoing(*NetSocket, APTR Meta). For NetServer listeners, the inherited field uses ERR Outgoing(*NetServer, *ClientSocket, APTR Meta).

To send data from a NetSocket object, call the Write() action. To send data from a NetServer to a connected client, call ClientSocket⇒Write() on the target client socket. 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.

For NetSocket clients, this is the remote port used by Connect(). For NetServer listeners, this inherited field is the local port to bind during initialisation.

 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.

For NetServer listeners this State value should not be used as it cannot reflect the state of all connected client sockets. When read from a NetServer, this inherited field reports NTC::MULTISTATE; each ClientSocket carries its own independent State value for accepted TCP connections.

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::MULTISTATEA NetServer reports MULTISTATE because accepted ClientSocket objects track their own states.
NTC::RESOLVINGThe host name is being resolved.

Actions

The following actions are currently supported:

DataFeedStreams raw data to the socket for writing.
ERR acDataFeed(*Object, OBJECTID Object, DATA Datatype, std::span<const int8_t> Buffer)
ParameterDescription
ObjectMust refer to the unique ID of the object that you represent. If you do not represent an object, set this parameter to the current task ID.
DatatypeThe type of data being sent.
BufferThe data being sent to the target object.

Data sent to a NetSocket through this action is written using the same buffered behaviour as Write().

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.
SystemCallA call to the host system has failed
ReadRead information from the socket.
ERR acRead(*Object, std::span<int8_t> Buffer, INT *Result)
ParameterDescription
BufferA mutable buffer that will receive the data.
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.
ArgsInvalid arguments passed to function
ReadError reading data
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, std::span<const int8_t> Buffer, INT *Result)
ParameterDescription
BufferA buffer containing the data that will be written 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 on a NetServer listener. 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, STRVIEW 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 a NetServer.
HostNotFoundHost name resolution failed.
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, STRVIEW 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.
ArgsInvalid multicast address.
NoSupportSocket is not configured for UDP mode.
SystemCallThe socket option to join the multicast group was rejected.
NullArgsFunction call missing argument value(s)
LeaveMulticastGroupLeave a multicast group (UDP only).
ERR ns::LeaveMulticastGroup(OBJECTPTR Object, STRVIEW 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.
ArgsInvalid multicast address.
NoSupportSocket is not configured for UDP mode.
SystemCallThe socket option to leave the multicast group was rejected.
NullArgsFunction call missing argument value(s)
RecvFromReceive a datagram packet from any address (UDP only).
ERR ns::RecvFrom(OBJECTPTR Object, struct IPAddress * Source, std::span<int8_t> Buffer, INT * BytesRead)
ParameterDescription
SourceSource IP address of the received packet.
BufferOutput buffer for received data.
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.
NullArgsFunction call missing argument value(s)
SendToSend a datagram packet to a specific address (UDP only).
ERR ns::SendTo(OBJECTPTR Object, struct IPAddress * Dest, std::span<const int8_t> Data, INT * BytesSent)
ParameterDescription
DestThe destination IP address (IPv4 or IPv6) and port number.
DataPointer to the data buffer to send.
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.
ArgsInvalid arguments passed to function
OutOfRangeInvalid port number specified.
BufferOverflowThe network buffer is full, retry later.
InvalidStateSocket is not configured for UDP mode.
NetworkUnreachableThe destination network is unreachable.
DataSizeThe size of a data chunk or buffer is incorrect
NullArgsInvalid arguments provided.
NetSocket class documentation © Paul Manias © 2005-2026

IPADDR Type

Address types for the IPAddress structure.

NameDescription
IPADDR::V4
IPADDR::V6
NetSocket module documentation © Paul Manias © 2005-2026

NSF Type

NetSocket options

NameDescription
NSF::BROADCASTEnable broadcast (UDP only).
NSF::DISABLE_SERVER_VERIFYDisable SSL server certificate verification for client sockets (testing only).
NSF::KEEP_ALIVEEnable TCP keep-alive probes using operating system defaults.
NSF::LOG_ALLPrint extra log messages.
NSF::MULTI_CONNECTAllow multiple connections from the same IP (NetServer only).
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-2026

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::MULTISTATEA NetServer reports MULTISTATE because accepted ClientSocket objects track their own states.
NTC::RESOLVINGThe host name is being resolved.
NetSocket module documentation © Paul Manias © 2005-2026

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