Skip to content

Socket

Spice
import "std/net/socket";

InAddr struct

Represents an IPv4 address

In6Addr struct

Represents an IPv6 address

SockAddrIn struct

Socket address for an IPv4 (AF_INET) endpoint

SockAddrIn6 struct

Socket address for an IPv6 (AF_INET6) endpoint

SockAddrUn struct

Socket address for a Unix domain (AF_UNIX) endpoint

Socket struct

A network socket, wrapping the listening socket file descriptor and the current connection

Methods

acceptConnection

Spice
public f<Result<int>> Socket.acceptConnection()

Accept an incoming connection to the socket and save the connection file desceiptor to the socket object.

Returns: Result<int> — Connection file descriptor

write

Spice
public f<long> Socket.write(string message)

Write a raw string to the socket.

Parameters

Name Type Description
message string Content of the message

Returns: long — Number of bytes written

write

Spice
public f<long> Socket.write(byte* content, unsigned long size)

Write an array of bytes to the socket. Note: The given buffer needs to be at least of the given size.

Parameters

Name Type Description
content byte* Buffer of bytes to send
size unsigned long Number of bytes from the buffer to send

Returns: long — Number of bytes written

read

Spice
public f<long> Socket.read(byte* buffer, long size)

Read n bytes from the socket to the given buffer. Note: The given buffer needs to be at least of the given size.

Parameters

Name Type Description
buffer byte* Buffer to write the result into
size long Number of bytes to read

Returns: long — Number of bytes written

close

Spice
public f<bool> Socket.close()

Closes the socket. This method should always be called by the user before exiting the program.

Returns: bool — Closing the connection was successful or not

Functions

openServerSocket

Spice
public f<Result<Socket>> openServerSocket(unsigned short port, int maxWaitingConnections = 5)

Opens a TCP server socket and exposes it to the given port. The maxWaitingConnections defines the maximum length to which the queue of pending connections may grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol support retransmission, the request may be ignored so that a later reattempt at connection succeeds.

Parameters

Name Type Description
port unsigned short Port to open the socket on
maxWaitingConnections int Maximum size of the queue of pending client connections (default: 5)

Returns: Result<Socket> — Socket file descriptor

openClientSocket

Spice
public f<Result<Socket>> openClientSocket(string host, unsigned short port)

Opens a TCP client socket and tries to connect it to a server socket.

Parameters

Name Type Description
host string Host to connect to
port unsigned short Post to connect to

Returns: Result<Socket> — Socket file descriptor

InAddrT alias

Alias for unsigned int.

InPortT alias

Alias for unsigned short.