silk.net.socket_native.
TCP and Unix socket connections and listeners, as ByteDuplex providers.
When to use#
To connect, call
connectResolvedwith endpoints fromsilk.net.resolver, orconnectUnixwith a socket path. The connection is lent to a callback and closed after it. UseconnectResolvedOwnedorconnectUnixOwnedto keep theConnectionyourself.To serve, call
listenorlistenUnix, thenacceptfor each client. UsewithAcceptedto get the connection and the peer address, and close them after.To drive sockets from your own readiness loop, such as one on
silk.io.reactor, use the calls that never wait:startConnectorstartConnectUnixwithConnection.finishConnect,Listener.tryAccept,Connection.tryRead,Connection.tryWrite, andConnection.tryWriteVectored. They returnWouldBlockwhen the socket is not ready. RegisterConnection.rawDescriptororListener.rawDescriptorwith the loop, and try again when it reports the socket ready.
A Connection provides ByteDuplex, so silk.http.exchange, silk.http.server, and
silk.io.buffered_duplex can use it.
Details#
All sockets are nonblocking. When a socket is not ready, the operation waits with
MonotonicClock.waitReady until the socket is ready or the deadline passes. The native clock
waits in the kernel poll and goes on as soon as the socket is ready; a task scheduler parks
only the task. One deadline covers all attempts of one connect or accept.
A connect tries the endpoints in their order, until one connects or the attempt limit is reached. A flush means that the kernel accepted the bytes, not that the peer got them.
Errors#
NativeSocketError tells the rule, the system error, or the deadline. When all endpoints
fail, AttemptsExhausted has the error of the last attempt.
Gotchas#
With a deadline of
None, a connect or accept can wait forever.Closing a Unix listener does not remove its socket file. Remove it yourself.
Scoped functions close the socket on return, error, and cancellation. A trap does not.
On Darwin, socket setup is not safe against a
forkin another thread.Supported targets are Windows x86_64 MSVC, Darwin x86_64 or aarch64, and GNU/Linux x86_64 or aarch64.
Windows uses nonblocking Winsock TCP sockets; Unix-domain operations return
FamilyUnsupported. Each live descriptor keeps Winsock initialized. Socket handles are pointer-sized.
Examples#
Connect to a local listener#
import silk.io.byte_duplex { ByteDuplex, ByteIoError, ReadTransfer }
import silk.core.effect { Effect }
import silk.system.monotonic_clock { MonotonicClock }
import silk.net.socket_native {
AcceptedView,
BoundAddress,
ConnectOptions,
Connection,
ListenOptions,
Listener,
NativeSocketError,
accept,
connectResolvedOwned,
listen,
withAccepted,
}
import silk.net.address { Endpoint, IpAddress, Ipv4Address, Port }
import silk.core.option { Option }
import silk.system.monotonic_clock_native { OsMonotonicClock }
import silk.time.mark { Mark }
// Reads one byte from the client and answers with one byte.
effect fn answer<'call>(view: &'call mut AcceptedView<'call>) -> i32
! ByteIoError
? &mut MonotonicClock {
let mut input: [u8; 1] = [0]
match move run ByteDuplex.readSome(&mut input, Option<Mark>.none())
|> Effect.provideMut<ByteDuplex>(&mut view.connection.*) {
ReadTransfer.Data { count } => {
if count != 1 || input[0] != 120 {
return 1
}
}
ReadTransfer.End => {
return 1
}
}
// One byte is always written at once, or the call fails.
let written = run ByteDuplex.writeSome(b"y", Option<Mark>.none())
|> Effect.provideMut<ByteDuplex>(&mut view.connection.*)
if written != 1 {
return 1
}
return 0
}
effect fn program() -> i32
! NativeSocketError | ByteIoError
? &mut MonotonicClock {
// Port 0 asks the system for a free port.
let local = Endpoint.make(
IpAddress.V4 { value: Ipv4Address.fromOctets([127, 0, 0, 1]) },
Port.fromU16(0)
)
let mut listener = run listen(local, ListenOptions.defaults())
let bound = match Listener.boundAddress(&listener) {
BoundAddress.Tcp { endpoint } => endpoint
_ => {
return 1
}
}
let targets = [bound]
let mut client = run connectResolvedOwned(
&targets,
ConnectOptions.defaults(),
Option<Mark>.none()
)
let sent = run ByteDuplex.writeSome(b"x", Option<Mark>.none())
|> Effect.provideMut<ByteDuplex>(&mut client)
if sent != 1 {
return 1
}
let accepted = run accept(&mut listener, Option<Mark>.none())
run Listener.close(&mut listener)
let served = run withAccepted<i32, ByteIoError>(move accepted, answer)
let mut reply: [u8; 1] = [0]
let read = run ByteDuplex.readSome(&mut reply, Option<Mark>.none())
|> Effect.provideMut<ByteDuplex>(&mut client)
run Connection.close(&mut client)
return match move read {
ReadTransfer.Data { count } => {
if served != 0 || count != 1 || reply[0] != 121 {
return 1
}
return 0
}
ReadTransfer.End => 1
}
}
effect fn failed<E>(error: E) -> i32 {
drop error
return 1
}
pub fn main() -> i32 {
let mut clock = OsMonotonicClock.make()
return run Effect.catchAll(program(), failed) |> Effect.provideMut<MonotonicClock>(&mut clock)
}Import as NativeSocket with import silk.net.socket_native { NativeSocket }.
Public declarations: 42.
RawSocket#
pub type RawSocket = i32A socket descriptor of the system: a POSIX file descriptor, or a pointer-sized Winsock
SOCKET on Windows.
Get it from Connection.rawDescriptor or Listener.rawDescriptor to register the socket
with a readiness queue, such as silk.io.reactor. The socket stays owned by its connection or
listener: do not close it.
ConnectionPhase#
pub enum ConnectionPhaseThe state of a Connection.
Connecting#
ConnectingThe connect has not finished.
Open#
OpenReads and writes are allowed.
WriteClosed#
WriteClosedThe write side is shut down. Reads are still allowed.
Closed#
ClosedThe socket is closed.
NativeSocketOperation#
pub enum NativeSocketOperationThe system call that failed.
Socket#
Socketsocket: create the socket.
Configure#
ConfigureSet descriptor flags or socket options.
Connect#
Connectconnect.
Bind#
Bindbind.
Listen#
Listenlisten.
GetSocketName#
GetSocketNamegetsockname: read the bound address.
GetPeerName#
GetPeerNamegetpeername: read the address of the peer.
Accept#
Acceptaccept.
ConvertAddress#
ConvertAddressConvert an address that the system returned.
Poll#
Pollpoll: check if the socket is ready.
GetSocketOption#
GetSocketOptiongetsockopt: read the error of the socket.
Read#
Readread.
Write#
Writewrite.
ShutdownWrite#
ShutdownWriteshutdown of the write side.
Close#
Closeclose.
Implementation Debug for NativeSocketOperation#
impl Debug for NativeSocketOperationOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant, such as Socket.
ListenerPhase#
pub enum ListenerPhaseThe state of a Listener.
Open#
OpenThe listener accepts clients.
Closed#
ClosedThe listener is closed.
ListenOptionsReason#
pub enum ListenOptionsReasonThe ListenOptions value that is not valid.
KernelBacklog#
KernelBacklogThe backlog is not 1 through 65535.
Implementation Debug for ListenOptionsReason#
impl Debug for ListenOptionsReasonOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant, such as KernelBacklog.
ListenOptionsError#
pub struct ListenOptionsErrorThe error of ListenOptions.make.
Field reason#
pub reason: ListenOptionsReasonThe value that is not valid.
Field value#
pub value: u64The value that you gave.
Implementation Debug for ListenOptionsError#
impl Debug for ListenOptionsErrorOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the fields, as ListenOptionsError { reason: ..., value: ... }.
InvalidBindReason#
pub enum InvalidBindReasonWhy a Unix socket path for listenUnix is not valid.
EmptyPath#
EmptyPathThe path is empty.
NulPath#
NulPathThe path has a NUL byte after the first byte.
AbstractPath#
AbstractPathThe path starts with a NUL byte, which names an abstract socket address. Only Linux has abstract addresses, so other systems return this.
Implementation Debug for InvalidBindReason#
impl Debug for InvalidBindReasonOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant, such as EmptyPath.
ConnectOptionsReason#
pub enum ConnectOptionsReasonThe ConnectOptions value that is not valid.
MaxAttempts#
MaxAttemptsThe attempt limit is not 1 through 1024.
Implementation Debug for ConnectOptionsReason#
impl Debug for ConnectOptionsReasonOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant, such as MaxAttempts.
ConnectOptionsError#
pub struct ConnectOptionsErrorThe error of ConnectOptions.make.
Field reason#
pub reason: ConnectOptionsReasonThe value that is not valid.
Field value#
pub value: u64The value that you gave.
Implementation Debug for ConnectOptionsError#
impl Debug for ConnectOptionsErrorOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the fields, as ConnectOptionsError { reason: ..., value: ... }.
InvalidEndpointReason#
pub enum InvalidEndpointReasonWhy the endpoints or the Unix socket path of a connect are not valid.
EmptyEndpoints#
EmptyEndpointsThe endpoint list is empty.
TooManyEndpoints#
TooManyEndpointsThere are more endpoints than the attempt limit.
EmptyPath#
EmptyPathThe path is empty.
NulPath#
NulPathThe path has a NUL byte after the first byte.
PathTooLong#
PathTooLongThe path is too long for a socket address.
AbstractPath#
AbstractPathThe path starts with a NUL byte, which names an abstract socket address. Only Linux has abstract addresses, so other systems return this.
Implementation Debug for InvalidEndpointReason#
impl Debug for InvalidEndpointReasonOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant, such as EmptyEndpoints.
AttemptFailure#
pub union AttemptFailureThe error of the last connect attempt, in AttemptsExhausted.
ConnectionRefused#
ConnectionRefusedThe peer refused the connection.
NetworkUnreachable#
NetworkUnreachableThe network cannot be reached.
AddressUnavailable#
AddressUnavailableThe address is not available.
NativeFailure#
NativeFailureAnother system error.
Field operation#
pub operation: NativeSocketOperationThe system call that failed.
Field errno#
pub errno: i32The host error code: POSIX errno, a Winsock WSA code, or a Win32 handle-configuration error.
Implementation Debug for AttemptFailure#
impl Debug for AttemptFailureOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant and its fields, such as ConnectionRefused.
NativeSocketError#
pub union NativeSocketErrorThe error of a socket operation: the rule that failed, the system error, or the deadline.
AttemptsExhausted#
AttemptsExhaustedAll connect attempts failed.
Field attempted#
pub attempted: usizeThe number of attempts.
Field last#
pub last: AttemptFailureThe error of the last attempt.
TimeRangeError#
TimeRangeErrorThe time of the next check does not fit in a Mark.
InvalidEndpoint#
InvalidEndpointThe endpoints or the socket path of a connect are not valid.
Field reason#
pub reason: InvalidEndpointReasonThe rule that failed.
Field offset#
pub offset: usizeThe byte position of the problem in the path.
Field limit#
pub limit: usizeThe largest allowed value.
InvalidBindAddress#
InvalidBindAddressThe socket path of listenUnix is not valid.
Field reason#
pub reason: InvalidBindReasonThe rule that failed.
Field offset#
pub offset: usizeThe byte position of the problem in the path.
PathTooLong#
PathTooLongThe socket path is too long for a socket address.
Field length#
pub length: usizeThe length of the path.
Field limit#
pub limit: usizeThe largest allowed length.
AddressInUse#
AddressInUseThe local address is in use.
InvalidNativeAddress#
InvalidNativeAddressThe system returned an address with a wrong family or length.
Field family#
pub family: i32The address family, or -1 if the address is too short.
Field length#
pub length: usizeThe length of the address.
UnsupportedPeerAddress#
UnsupportedPeerAddressThe peer has an address form that is not supported.
Field family#
pub family: i32The address family, or -1 if the address is too short.
Field length#
pub length: usizeThe length of the address.
FamilyUnsupported#
FamilyUnsupportedThe system does not support the address family.
PermissionDenied#
PermissionDeniedThe system denied the operation.
ConnectionRefused#
ConnectionRefusedThe peer refused the connection.
NetworkUnreachable#
NetworkUnreachableThe network cannot be reached.
AddressUnavailable#
AddressUnavailableThe address is not available.
SystemResources#
SystemResourcesThe system does not have the resources, such as descriptors.
Timeout#
TimeoutThe deadline passed.
Closed#
ClosedThe socket is closed.
WriteClosed#
WriteClosedThe write side is shut down.
InvalidTransferCount#
InvalidTransferCountThe system returned a transfer count that is not valid.
Field operation#
pub operation: ByteIoOperationThe operation.
Field count#
pub count: usizeThe count that the system returned.
Field limit#
pub limit: usizeThe largest valid count.
NativeFailure#
NativeFailureAnother system error.
Field operation#
pub operation: NativeSocketOperationThe system call that failed.
Field errno#
pub errno: i32The host error code: POSIX errno, a Winsock WSA code, or a Win32 handle-configuration error.
Implementation Debug for NativeSocketError#
impl Debug for NativeSocketErrorOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant and its fields, such as AttemptsExhausted { ... }.
NativeSocket#
pub struct NativeSocketAn empty marker type for this module.
ConnectOptions#
pub struct ConnectOptionsThe settings of a connect: Nagle and the attempt limit.
ListenOptions#
pub struct ListenOptionsThe settings of a listener: the backlog, address reuse, and IPv6-only mode.
UnixSocketPath#
pub struct UnixSocketPathA copy of a Unix socket path, at most 108 bytes.
BoundAddress#
pub union BoundAddressThe local address of a Listener.
Tcp#
TcpA TCP listener.
Field endpoint#
pub endpoint: EndpointThe address and port. With port 0 in listen, this is the port that the system chose.
Unix#
UnixA Unix socket listener.
Field path#
pub path: UnixSocketPathThe socket path.
UnixPeerAddress#
pub union UnixPeerAddressThe address of a Unix socket client.
Unnamed#
UnnamedThe client socket has no path. This is normal for a client.
Pathname#
PathnameThe client socket has a path.
Field path#
pub path: UnixSocketPathThe path.
PeerAddress#
pub union PeerAddressThe address of an accepted client.
Tcp#
TcpA TCP client.
Field endpoint#
pub endpoint: EndpointThe address and port of the client.
Unix#
UnixA Unix socket client.
Field peer#
pub peer: UnixPeerAddressThe address of the client.
Received#
pub union ReceivedThe outcome of Connection.tryRead.
Data#
DataThe read copied count bytes into the buffer. count is 0 only for an empty buffer.
Field count#
pub count: usizeThe number of bytes read.
End#
EndThe peer shut down its write side, and every byte before that was read.
WouldBlock#
WouldBlockNo bytes are ready. Try again when the socket is readable.
Sent#
pub union SentThe outcome of Connection.tryWrite and Connection.tryWriteVectored.
Count#
CountThe kernel took the first count bytes. count is 0 only when there was nothing to send.
Field count#
pub count: usizeThe number of bytes sent.
WouldBlock#
WouldBlockThe send buffer is full. Try again when the socket is writable.
Incoming#
pub union IncomingThe outcome of Listener.tryAccept.
Client#
ClientA client connected.
Field accepted#
pub accepted: AcceptedThe open connection and the address of the client.
WouldBlock#
WouldBlockNo client is waiting. Try again when the listener is readable.
ConnectProgress#
pub enum ConnectProgressThe outcome of Connection.finishConnect.
Connected#
ConnectedThe connect finished. The connection is open.
InProgress#
InProgressThe connect goes on. Try again when the socket is writable.
Implementation Copy for ConnectOptionsError#
impl Copy for ConnectOptionsErrorImplementation Copy for AttemptFailure#
impl Copy for AttemptFailureImplementation Copy for NativeSocketError#
impl Copy for NativeSocketErrorImplementation Copy for ConnectOptions#
impl Copy for ConnectOptionsImplementation Copy for ListenOptionsError#
impl Copy for ListenOptionsErrorImplementation Copy for ListenOptions#
impl Copy for ListenOptionsImplementation Copy for UnixSocketPath#
impl Copy for UnixSocketPathImplementation Copy for BoundAddress#
impl Copy for BoundAddressImplementation Copy for UnixPeerAddress#
impl Copy for UnixPeerAddressImplementation Copy for PeerAddress#
impl Copy for PeerAddressImplementation ConnectOptions#
impl ConnectOptionsAssociated function make#
pub fn make(noDelay: bool, maxAttempts: usize) -> Result<ConnectOptions, ConnectOptionsError>Returns connect options.
Errors#
ConnectOptionsError if maxAttempts is not 1 through 1024.
Associated function defaults#
pub fn defaults() -> ConnectOptionsReturns the default connect options: Nagle on, and 64 attempts.
Method noDelay#
pub fn noDelay(self: &Self) -> boolReturns whether Nagle is off (TCP_NODELAY).
Method maxAttempts#
pub fn maxAttempts(self: &Self) -> usizeReturns the attempt limit.
Implementation ListenOptions#
impl ListenOptionsAssociated function make#
pub fn make(kernelBacklog: usize, reuseAddress: bool, ipv6Only: bool) -> Result<ListenOptions, ListenOptionsError>Returns listen options.
Windows defaults to an exclusive bind when reuseAddress is false. When true, Windows'
SO_REUSEADDR permits binding over an existing listener, unlike Unix's usual reuse behavior.
Errors#
ListenOptionsError if kernelBacklog is not 1 through 65535.
Associated function defaults#
pub fn defaults() -> ListenOptionsReturns the default listen options: a backlog of 128, no address reuse, and IPv6 listeners that take only IPv6.
Method kernelBacklog#
pub fn kernelBacklog(self: &Self) -> usizeReturns the backlog of the kernel.
Method reuseAddress#
pub fn reuseAddress(self: &Self) -> boolReturns whether the listener sets SO_REUSEADDR.
Method ipv6Only#
pub fn ipv6Only(self: &Self) -> boolReturns whether an IPv6 listener takes only IPv6 clients (IPV6_V6ONLY). When false, it
also takes IPv4 clients, as IPv4-mapped IPv6 addresses.
Implementation UnixSocketPath#
impl UnixSocketPathMethod bytes#
pub fn bytes(self: &Self) -> &[u8]Returns the path bytes.
Connection#
pub struct ConnectionAn open socket connection. It provides ByteDuplex, so silk.http.exchange,
silk.http.server, and silk.io.buffered_duplex can use it.
Details#
The socket is nonblocking. When it is not ready, an operation waits for the poll interval with
MonotonicClock, then tries again. So an idle wait costs about one check for each interval. A
flush means that the kernel accepted the bytes, not that the peer got them.
Listener#
pub struct ListenerA listening socket and its local address.
Accepted#
pub struct AcceptedA connection from accept, with the address of the client. Use it with withAccepted.
AcceptedView#
pub struct AcceptedView<'a>The connection and the client address that withAccepted lends to its callback.
Field connection#
pub connection: &'a mut ConnectionThe connection. It is valid only in the callback.
Field peer#
pub peer: &'a PeerAddressThe address of the client.
AcceptedContext#
pub interface AcceptedContext<A, E, ?CallbackRequirements, ?ContextRequirements>A value that serves one accepted connection. See withAcceptedContext.
Details#
Implement it when the code that serves the connection owns state that is moved in, such as a
handler. use gets the value one time.
Operation use#
effect<'call> fn use<'call>(
context: Self,
view: &'call mut AcceptedView<'call>,
) -> A ! E ? CallbackRequirements | ContextRequirementsServes the connection in view, with context.
ConnectionHalves#
pub struct ConnectionHalvesThe two halves of a connection, from Connection.split.
Field reader#
pub reader: ConnectionThe half to read from.
Field writer#
pub writer: ConnectionThe half to write to.
Implementation Connection#
impl ConnectionMethod phase#
pub fn phase(self: &Self) -> ConnectionPhaseReturns the state of the connection.
Method split#
pub effect fn split(self: Self) -> ConnectionHalves ! OutOfMemoryError ? &mut AllocatorSplits the connection into a half to read from and a half to write to, so that one fiber can wait for input while another one writes.
Details#
Both halves are connections on the same socket, and each keeps its own state. Use reader
only to read and writer only to write. ByteDuplex.shutdownWrite on writer closes the
write direction of the socket. Closing or dropping a half releases it; the socket closes when
both halves are closed or dropped.
Errors#
OutOfMemoryError if the shared socket cannot be allocated. The connection is then closed.
Method idle#
pub fn idle(self: &Self) -> boolReturns true when the connection is open and the peer has sent nothing and not closed it, so a new request can go out on it. It does not wait.
Method close#
pub effect fn close(self: &mut Self) -> () ! NativeSocketErrorCloses the connection. A second call does nothing.
The scoped functions close the connection too, and ignore a close error.
Implementation Listener#
impl ListenerMethod phase#
pub fn phase(self: &Self) -> ListenerPhaseReturns the state of the listener.
Method boundAddress#
pub fn boundAddress(self: &Self) -> BoundAddressReturns the local address of the listener.
Method close#
pub effect fn close(self: &mut Self) -> () ! NativeSocketErrorCloses the listener. A second call does nothing. It does not remove a Unix socket file.
Implementation Accepted#
impl AcceptedMethod peer#
pub fn peer(self: &Self) -> PeerAddressReturns the address of the client.
Method connectionPhase#
pub fn connectionPhase(self: &Self) -> ConnectionPhaseReturns the state of the connection.
Method intoConnection#
pub fn intoConnection(self: Self) -> ConnectionTakes the connection out of self, and returns it.
When to use#
Use it to keep a connection open past one callback, such as a client served across the
frames of an event loop. Use withAccepted when one callback serves the whole connection.
Details#
Read peer first if you need the client address: it goes with self. Close the connection
with Connection.close to see a close error. Dropping it closes it too, and ignores the error.
listen#
pub effect fn listen(endpoint: Endpoint, options: ListenOptions) -> Listener ! NativeSocketErrorMakes a TCP listener on endpoint, IPv4 or IPv6.
With port 0, the system chooses a free port. Listener.boundAddress returns it.
Errors#
AddressInUse, PermissionDenied, SystemResources, or another NativeSocketError.
listenUnix#
pub effect fn listenUnix(path: &[u8], options: ListenOptions) -> Listener ! NativeSocketErrorMakes a Unix socket listener at path.
path is a file path, relative to the current directory unless it starts with /. On Linux, a
path that starts with a NUL byte is an abstract name: the bytes after the NUL name the socket
and no file is made. Other systems reject an abstract name with AbstractPath.
It does not remove an old file at path before, or the file after close.
Errors#
InvalidBindAddress or PathTooLong if path is not valid. AddressInUse if a file exists.
Windows returns FamilyUnsupported for Unix-domain sockets before creating a socket.
accept#
pub effect fn accept(
listener: &mut Listener,
deadline: Option<Mark>,
) -> Accepted ! NativeSocketError ? &mut MonotonicClockWaits for the next client, and returns its connection.
The listener stays open. deadline is absolute, and covers all checks of this call.
Errors#
Timeout if the deadline passes. Closed if the listener is closed.
withListener#
pub effect fn withListener<'env, A, E, ?CallbackRequirements>(
listener: Listener,
callback: for<'call> once fn<'env>(
&'call mut Listener
) -> once Effect<'call; A ! E ? CallbackRequirements>,
) -> A ! E ? CallbackRequirementsLends listener to callback, and closes it after, also on error or cancellation.
withAccepted#
pub effect fn withAccepted<'env, A, E, ?CallbackRequirements>(
accepted: Accepted,
callback: for<'call> once fn<'env>(
&'call mut AcceptedView<'call>
) -> once Effect<'call; A ! E ? CallbackRequirements>,
) -> A ! E ? CallbackRequirements
where CallbackRequirements in Without<CallbackRequirements, ByteDuplex>Lends the connection and the client address of accepted to callback, and closes the
connection after, also on error or cancellation.
withAcceptedContext#
pub effect<'env> fn withAcceptedContext<
A,
E,
?CallbackRequirements,
?ContextRequirements,
C: AcceptedContext<A, E, CallbackRequirements ? ContextRequirements> + 'env,
'env,
>(
accepted: Accepted,
context: C,
) -> A ! E ? CallbackRequirements | ContextRequirements
where CallbackRequirements in Without<CallbackRequirements, ByteDuplex>,
ContextRequirements in Without<ContextRequirements, ByteDuplex>Serves accepted with context, and closes the connection after.
Details#
context is used one time. The connection is closed on success, error, and cancellation. A
close error never replaces the result.
connectResolvedOwned#
pub effect fn connectResolvedOwned(
endpoints: &[Endpoint],
options: ConnectOptions,
deadline: Option<Mark>,
) -> Connection ! NativeSocketError ? &mut MonotonicClockConnects to the first of endpoints that accepts, and returns the connection.
Errors#
InvalidEndpointifendpointsis empty or longer than the attempt limit.AttemptsExhaustedif no endpoint accepts.Timeoutifdeadlinepasses.
connectUnixOwned#
pub effect fn connectUnixOwned(
path: &[u8],
options: ConnectOptions,
deadline: Option<Mark>,
) -> Connection ! NativeSocketError ? &mut MonotonicClockConnects to the Unix socket at path, and returns the connection.
path is a file path, relative to the current directory unless it starts with /. On Linux, a
path that starts with a NUL byte is an abstract name: the bytes after the NUL name the socket
and no file is used. Other systems reject an abstract name with AbstractPath.
Errors#
InvalidEndpoint if path is not valid. Timeout if deadline passes.
Windows returns FamilyUnsupported for Unix-domain sockets before creating a socket.
connectResolved#
pub effect fn connectResolved<'env, A, E, ?CallbackRequirements>(
endpoints: &[Endpoint],
options: ConnectOptions,
deadline: Option<Mark>,
callback: for<'call> once fn<'env>(
&'call mut Connection
) -> once Effect<'call; A ! E ? CallbackRequirements>,
) -> A ! E | NativeSocketError ? CallbackRequirements | &mut MonotonicClock
where CallbackRequirements in Without<CallbackRequirements, ByteDuplex>Connects to the first of endpoints that accepts, lends the connection to callback, and
closes it after, also on error or cancellation. A trap does not close it.
Errors#
The error of
callback.InvalidEndpointifendpointsis empty or longer than the attempt limit.AttemptsExhaustedif no endpoint accepts. It has the error of the last attempt.Timeoutifdeadlinepasses. One deadline covers all attempts.
Gotchas#
With a deadline of None, the connect can wait forever.
connectUnix#
pub effect fn connectUnix<'env, A, E, ?CallbackRequirements>(
path: &[u8],
options: ConnectOptions,
deadline: Option<Mark>,
callback: for<'call> once fn<'env>(
&'call mut Connection
) -> once Effect<'call; A ! E ? CallbackRequirements>,
) -> A ! E | NativeSocketError ? CallbackRequirements | &mut MonotonicClock
where CallbackRequirements in Without<CallbackRequirements, ByteDuplex>Connects to the Unix socket at path, lends the connection to callback, and closes it after,
also on error or cancellation. A trap does not close it.
path is a file path, relative to the current directory unless it starts with /. On Linux, a
path that starts with a NUL byte is an abstract name: the bytes after the NUL name the socket
and no file is used. Other systems reject an abstract name with AbstractPath.
Errors#
The error of
callback.InvalidEndpointifpathis not valid.Timeoutifdeadlinepasses.FamilyUnsupportedon Windows, before creating a socket.
Implementation Connection#
impl ConnectionImplementation ByteDuplex for Connection#
impl ByteDuplex for ConnectionOperation readSomeRaw#
readSomeRaw: Connection.readConnectionOperation writeSomeRaw#
writeSomeRaw: Connection.writeConnectionOperation writeSomeVectoredRaw#
writeSomeVectoredRaw: Connection.writeConnectionVectoredOperation flushRaw#
flushRaw: Connection.flushConnectionOperation shutdownWriteRaw#
shutdownWriteRaw: Connection.shutdownConnectionOperation closeRaw#
closeRaw: Connection.closeByteConnectionstartConnect#
pub effect fn startConnect(endpoint: Endpoint, options: ConnectOptions) -> Connection
! NativeSocketErrorMakes a TCP socket for endpoint, IPv4 or IPv6, and starts its connect without waiting.
When to use#
Use it when your own loop waits for sockets, such as with silk.io.reactor. Use
connectResolvedOwned to wait for the connect in this call.
Details#
The socket is nonblocking and close-on-exec, and Nagle is off when options.noDelay() is set.
The returned connection is Open when the connect finished at once, else Connecting. For a
Connecting connection, wait until Connection.rawDescriptor is writable, then call
Connection.finishConnect. The attempt limit and poll interval of options are not used.
Errors#
ConnectionRefused, NetworkUnreachable, AddressUnavailable, PermissionDenied,
SystemResources, or another NativeSocketError, if the system refused the connect at once.
startConnectFrom#
pub effect fn startConnectFrom(local: Endpoint, endpoint: Endpoint, options: ConnectOptions) -> Connection
! NativeSocketErrorMakes a TCP socket bound to the local address local, and starts its connect to endpoint
without waiting.
When to use#
Use it to choose the local address or port of a connection, as Node's localAddress and
localPort do. Otherwise use startConnect.
Details#
It works as startConnect does, with a bind to local before the connect. Port 0 in local
lets the system choose the port.
Errors#
FamilyUnsupported if local and endpoint are not of one family. AddressInUse,
AddressUnavailable, or NativeFailure with operation Bind if the bind fails. Otherwise the
errors of startConnect.
startConnectUnix#
pub effect fn startConnectUnix(path: &[u8], options: ConnectOptions) -> Connection
! NativeSocketErrorMakes a Unix socket for path, and starts its connect without waiting.
path is a file path, relative to the current directory unless it starts with /. On Linux, a
path that starts with a NUL byte is an abstract name: the bytes after the NUL name the socket
and no file is used. Other systems reject an abstract name with AbstractPath.
When to use#
Use it when your own loop waits for sockets, such as with silk.io.reactor. Use
connectUnixOwned to wait for the connect in this call.
Details#
The socket is nonblocking and close-on-exec. The returned connection is Open when the
connect finished at once, else Connecting. For a Connecting connection, wait until
Connection.rawDescriptor is writable, then call Connection.finishConnect. The options
of options are not used.
Errors#
InvalidEndpoint or PathTooLong if path is not valid. ConnectionRefused if no listener
is at path. On Linux, NativeFailure with operation Connect and errno EAGAIN (11) if the
backlog of the listener is full. Windows returns FamilyUnsupported.
Implementation Connection#
impl ConnectionMethod rawDescriptor#
pub fn rawDescriptor(self: &Self) -> RawSocketReturns the socket descriptor, to register it with a readiness queue such as
silk.io.reactor.
Details#
The connection still owns the socket: do not close it, and remove it from the queue before
the connection is closed or dropped. After a close, it returns the invalid descriptor (-1, or
INVALID_SOCKET on Windows). Both halves of a split connection return the same descriptor.
Method finishConnect#
pub effect fn finishConnect(self: &mut Self) -> ConnectProgress ! NativeSocketErrorChecks a connect from startConnect or startConnectUnix, without waiting.
Details#
Call it when the socket is writable. It polls the socket once with no timeout, then
returns Connected and sets the phase to Open when the connect finished, and
InProgress while it goes on. It returns Connected for a
connection that is already open.
Errors#
The error of the failed connect, such as ConnectionRefused or NetworkUnreachable, or
NativeFailure with operation Connect or Poll and the errno. The connection stays
Connecting: close it after you remove it from your readiness queue. Closed if it is
closed.
Method tryRead#
pub effect fn tryRead(self: &mut Self, output: &mut [u8]) -> Received ! NativeSocketErrorReads the bytes that are ready, at most output.length, without waiting.
When to use#
Use it when your own loop waits for sockets, such as with silk.io.reactor. Use
ByteDuplex.readSome to wait for bytes in this call.
Details#
It returns Data with the count, End when the peer shut down its write side, and
WouldBlock when no bytes are ready. After End, every call returns End. An empty
output returns Data with count 0 and reads nothing.
Errors#
Closed if the connection is closed or its connect has not finished. NativeFailure with
operation Read and the errno, such as ECONNRESET. The connection stays open: close it
after you remove it from your readiness queue.
Method tryWrite#
pub effect fn tryWrite(self: &mut Self, input: &[u8]) -> Sent ! NativeSocketErrorSends the bytes of input that fit in the send buffer, without waiting.
When to use#
Use it when your own loop waits for sockets, such as with silk.io.reactor. Use
ByteDuplex.writeSome to wait for room in this call.
Details#
It returns Count with the bytes sent, which can be fewer than input.length, and
WouldBlock when the buffer is full. An empty input returns Count 0. A send to a closed
peer fails and does not raise SIGPIPE.
Errors#
WriteClosed after shutdownWrite. Closed if the connection is closed or its connect has
not finished. NativeFailure with operation Write and the errno, such as EPIPE or
ECONNRESET.
Method tryWriteVectored#
pub effect fn tryWriteVectored(self: &mut Self, inputs: &[&[u8]]) -> Sent ! NativeSocketErrorSends the slices of inputs in order, as many bytes as fit in the send buffer, in one
system call and without waiting.
Details#
One call sends from at most eight non-empty slices; empty slices are skipped. It returns
Count with the bytes sent, counted across the slices, and WouldBlock when the buffer is
full. No slices, or only empty ones, return Count 0. A send to a closed peer fails and does
not raise SIGPIPE.
Errors#
WriteClosed after shutdownWrite. Closed if the connection is closed or its connect has
not finished. NativeFailure with operation Write and the errno, such as EPIPE or
ECONNRESET.
Method shutdownWrite#
pub effect fn shutdownWrite(self: &mut Self) -> () ! NativeSocketErrorShuts down the write side, so the peer reads the end after the bytes already sent. Reads are still allowed. A second call does nothing. It does not wait.
Errors#
Closed if the connection is closed or its connect has not finished. NativeFailure with
operation ShutdownWrite and the errno, such as ENOTCONN after the peer reset.
Method setNoDelay#
pub effect fn setNoDelay(self: &mut Self, enabled: bool) -> () ! NativeSocketErrorTurns Nagle off (TCP_NODELAY set) when enabled is true, and on when it is false.
Errors#
Closed if the connection is closed. NativeFailure with operation Configure and the
errno, such as EOPNOTSUPP on a Unix socket.
Method setKeepAlive#
pub effect fn setKeepAlive(self: &mut Self, enabled: bool, idleSeconds: u32) -> ()
! NativeSocketErrorTurns TCP keepalive probes on or off (SO_KEEPALIVE).
Details#
With enabled and an idleSeconds above 0, the first probe goes after the connection is
idle for idleSeconds (TCP_KEEPIDLE on Linux, TCP_KEEPALIVE on Darwin and Windows). With
idleSeconds 0, the system default stays. The probe interval and count are the system
defaults. idleSeconds is not used when enabled is false.
Errors#
Closed if the connection is closed. NativeFailure with operation Configure and the
errno, such as EINVAL for an idle time that the system does not allow.
Method localEndpoint#
pub effect fn localEndpoint(self: &Self) -> Endpoint ! NativeSocketErrorReturns the local address and port of a TCP connection.
Errors#
Closed if the connection is closed. InvalidNativeAddress for a Unix socket connection.
NativeFailure with operation GetSocketName and the errno.
Method peerEndpoint#
pub effect fn peerEndpoint(self: &Self) -> Endpoint ! NativeSocketErrorReturns the address and port of the peer of a TCP connection.
Errors#
Closed if the connection is closed. InvalidNativeAddress for a Unix socket connection.
NativeFailure with operation GetPeerName and the errno, such as ENOTCONN before the
connect finished or after the peer reset.
Implementation Listener#
impl ListenerMethod rawDescriptor#
pub fn rawDescriptor(self: &Self) -> RawSocketReturns the socket descriptor, to register it with a readiness queue such as
silk.io.reactor. The listener is readable when a client waits.
Details#
The listener still owns the socket: do not close it, and remove it from the queue before the
listener is closed or dropped. After a close, it returns the invalid descriptor (-1, or
INVALID_SOCKET on Windows).
Method tryAccept#
pub effect fn tryAccept(self: &mut Self) -> Incoming ! NativeSocketErrorAccepts the next client if one waits, without waiting.
When to use#
Use it when your own loop waits for sockets, such as with silk.io.reactor. Use accept
to wait for a client in this call.
Details#
It returns Client with the open connection, which is nonblocking and close-on-exec with
Nagle on, and WouldBlock when no client waits. A client that failed before it was
accepted is skipped.
Errors#
Closed if the listener is closed. SystemResources when the process or system is out of
descriptors or memory. NativeFailure with operation Accept and the errno.
Category: Networking.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, wasm64-unknown-unknown.