Library Moduleswift-nio 2.74.0NIOCore
NIOCore
The core abstractions that make up SwiftNIO.
index.mdimport NIOCore
Module information
- Declarations
- 1480
- Symbols
- 2237
Overview
NIOCore
contains the fundamental abstractions that are used in all SwiftNIO programs. The goal of this module is to be platform-independent, and to be the most-common building block used for NIO protocol implementations.
More specialized modules provide concrete implementations of many of the abstractions defined in NIOCore.
Articles
NIO and Swift Concurrency
This article explains how to interface between NIO and Swift Concurrency.
Read MoreWriting length-prefixed data in ByteBuffer
This article explains how to write data prefixed with a length, where the length could be encoded in various ways.
Read More
Event Loops and Event Loop Groups
protocol EventLoopGroup
Provides an endless stream of
EventLoop
s to use.protocol EventLoop
An EventLoop processes IO / tasks in an endless loop for
Channel
s until it’s closed.enum NIOEventLoopGroupProvider
This type is intended to be used by libraries which use NIO, and offer their users either the option to
.share
an existing event loop group or create (and manage) a new one (.createNew
) and let it be managed by given library and its lifecycle.struct EventLoopIterator
An iterator over the
EventLoop
s forming anEventLoopGroup
.struct Scheduled<T>
Returned once a task was scheduled on the
EventLoop
for later execution.class RepeatedTask
Returned once a task was scheduled to be repeatedly executed on the
EventLoop
.struct NIOLoopBound<Value>
NIOLoopBound
is an always-Sendable
, value-typed container allowing you access tovalue
if and only if you are accessing it on the rightEventLoop
.class NIOLoopBoundBox<Value>
NIOLoopBoundBox
is an always-Sendable
, reference-typed container allowing you access tovalue
if and only if you are accessing it on the rightEventLoop
.
Channels and Channel Handlers
protocol Channel
A
Channel
is easiest thought of as a network socket. But it can be anything that is capable of I/O operations such as read, write, connect, and bind.protocol MulticastChannel
A
MulticastChannel
is aChannel
that supports IP multicast operations: that is, a channel that can join multicast groups.protocol ChannelHandler
Base protocol for handlers that handle I/O events or intercept an I/O operation.
protocol ChannelOutboundHandler
ChannelHandler
which handles outbound I/O events or intercept an outbound I/O operation for aChannel
.protocol ChannelInboundHandler
ChannelHandler
which handles inbound I/O events for aChannel
.typealias ChannelDuplexHandler
A combination of
ChannelInboundHandler
andChannelOutboundHandler
.class ChannelHandlerContext
Every
ChannelHandler
has – when added to aChannelPipeline
– a correspondingChannelHandlerContext
which is the wayChannelHandler
s can interact with otherChannelHandler
s in the pipeline.class ChannelPipeline
A list of
ChannelHandler
s that handle or intercept inbound events and outbound operations of aChannel
.ChannelPipeline
implements an advanced form of the Intercepting Filter pattern to give a user full control over how an event is handled and how theChannelHandler
s in a pipeline interact with each other.protocol RemovableChannelHandler
A
RemovableChannelHandler
is aChannelHandler
that can be dynamically removed from aChannelPipeline
whilst theChannel
is operating normally. ARemovableChannelHandler
is required to remove itself from theChannelPipeline
(usingChannelHandlerContext.leavePipeline
) as soon as possible.struct NIOAny
NIOAny
is an opaque container for values of any type, similar to Swift’s builtinAny
type. Contrary toAny
the overhead ofNIOAny
depends on the the type of the wrapped value. Certain types that are important for the performance of a SwiftNIO application likeByteBuffer
,FileRegion
andAddressEnvelope<ByteBuffer>
can be expected to be wrapped almost without overhead. All others will have similar performance as if they were passed as anAny
asNIOAny
just likeAny
will contain them within an existential container.enum ChannelEvent
An
Channel
related event that is passed through theChannelPipeline
to notify the user.enum CloseMode
Specify what kind of close operation is requested.
struct ChannelShouldQuiesceEvent
A
Channel
user event that is sent when theChannel
has been asked to quiesce.
Buffers and Files
struct ByteBuffer
ByteBuffer
stores contiguously allocated raw bytes. It is a random and sequential accessible sequence of zero or more bytes (octets).struct ByteBufferView
A view into a portion of a
ByteBuffer
.struct ByteBufferAllocator
The preferred allocator for
ByteBuffer
values. The allocation strategy is opaque but is currently libc’smalloc
,realloc
andfree
.enum Endianness
Endianness refers to the sequential order in which bytes are arranged into larger numerical values when stored in memory or when transmitted over digital links.
class NIOFileHandle
A
NIOFileHandle
is a handle to an open file.protocol FileDescriptor
struct FileRegion
A
FileRegion
represent a readable portion usually created to be sent over the network.typealias NIOPOSIXFileMode
enum IOData
IOData
unifies standard SwiftNIO types that are raw bytes of data; currentlyByteBuffer
andFileRegion
.
Futures and Promises
class EventLoopFuture<Value>
Holder for a result that will be provided later.
struct EventLoopPromise<Value>
A promise to provide a result later.
Configuring Channels
protocol ChannelOption
A configuration option that can be set on a
Channel
to configure different behaviour.protocol NIOSynchronousChannelOptions
struct ChannelOptions
Provides
ChannelOption
s to be used with aChannel
,Bootstrap
orServerBootstrap
.protocol SocketOptionProvider
This protocol defines an object, most commonly a
Channel
, that supports setting and getting socket options (viasetsockopt
/getsockopt
or similar). It provides a strongly typed API that makes working with larger, less-common socket options easier than theChannelOption
API allows.protocol RecvByteBufferAllocator
Allocates
ByteBuffer
s to be used to read bytes from aChannel
and records the number of the actual bytes that were used.struct AdaptiveRecvByteBufferAllocator
RecvByteBufferAllocator
which will gracefully increment or decrement the buffer size on the feedback that was recorded.struct FixedSizeRecvByteBufferAllocator
RecvByteBufferAllocator
which will always return aByteBuffer
with the same fixed size no matter what was recorded.typealias AllocatorOption
typealias AllowRemoteHalfClosureOption
typealias AutoReadOption
typealias BacklogOption
typealias ConnectTimeoutOption
typealias DatagramVectorReadMessageCountOption
typealias MaxMessagesPerReadOption
typealias RecvAllocatorOption
typealias SocketOption
typealias SocketOptionLevel
typealias SocketOptionName
typealias SocketOptionValue
typealias WriteBufferWaterMarkOption
typealias WriteBufferWaterMark
typealias WriteSpinOption
Message Oriented Protocol Helpers
struct AddressedEnvelope<DataType>
A data structure for processing addressed datagrams, such as those used by UDP.
struct NIOPacketInfo
enum NIOExplicitCongestionNotificationState
Possible Explicit Congestion Notification States
Generic Bootstraps
struct NIOClientTCPBootstrap
NIOClientTCPBootstrap
is a bootstrap that allows you to bootstrap client TCP connections using NIO on BSD Sockets, NIO Transport Services, or other ways.protocol NIOClientTCPBootstrapProtocol
NIOClientTCPBootstrapProtocol
is implemented by various underlying transport mechanisms. Typically, this will be the BSD Sockets API implemented byClientBootstrap
.protocol NIOClientTLSProvider
struct NIOInsecureNoTLS<Bootstrap>
Simple Message Handling
protocol ByteToMessageDecoder
ByteToMessageDecoder
s decode bytes in a stream-like fashion fromByteBuffer
to another message type.protocol WriteObservingByteToMessageDecoder
Some
ByteToMessageDecoder
s need to observewrite
s (which are outbound events).ByteToMessageDecoder
s which implement theWriteObservingByteToMessageDecoder
protocol will be notified about every outbound write.enum DecodingState
State of the current decoding process.
class ByteToMessageHandler<Decoder>
A handler which turns a given
ByteToMessageDecoder
into aChannelInboundHandler
that can then be added to aChannelPipeline
.protocol NIOSingleStepByteToMessageDecoder
A simplified version of
ByteToMessageDecoder
that can generate zero or one messages for each invocation ofdecode
ordecodeLast
. Havingdecode
anddecodeLast
return an optional message avoids re-entrancy problems, since the functions relinquish exclusive access to theByteBuffer
when returning. This allows for greatly simplified processing.class NIOSingleStepByteToMessageProcessor<Decoder>
NIOSingleStepByteToMessageProcessor
uses aNIOSingleStepByteToMessageDecoder
to produce messages from a stream of incoming bytes. It works likeByteToMessageHandler
but may be used outside of the channel pipeline. This allows processing of wrapped protocols in a general way.protocol MessageToByteEncoder
A protocol for straightforward encoders which encode custom messages to
ByteBuffer
s. To add aMessageToByteEncoder
to aChannelPipeline
, usechannel.pipeline.addHandler(MessageToByteHandler(myEncoder)
.class MessageToByteHandler<Encoder>
A handler which turns a given
MessageToByteEncoder
into aChannelOutboundHandler
that can then be added to aChannelPipeline
.
Core Channel Handlers
class AcceptBackoffHandler
A
ChannelHandler
that implements a backoff for aServerChannel
when accept produces anIOError
. These errors are often recoverable by reducing the rate at which we call accept.class BackPressureHandler
ChannelHandler implementation which enforces back-pressure by stopping to read from the remote peer when it cannot write back fast enough. It will start reading again once pending data was written.
class NIOCloseOnErrorHandler
A
ChannelInboundHandler
that closes the channel when an error is caughtclass IdleStateHandler
Triggers an IdleStateEvent when a Channel has not performed read, write, or both operation for a while.
Async Sequences
struct NIOAsyncSequenceProducer<Element, Strategy, Delegate>
This is an
AsyncSequence
that supports a unicastAsyncIterator
.struct NIOThrowingAsyncSequenceProducer<Element, Failure, Strategy, Delegate>
This is an
AsyncSequence
that supports a unicastAsyncIterator
.protocol NIOAsyncSequenceProducerBackPressureStrategy
A protocol for the back-pressure strategy of the
NIOAsyncSequenceProducer
.enum NIOAsyncSequenceProducerBackPressureStrategies
protocol NIOAsyncSequenceProducerDelegate
The delegate of
NIOAsyncSequenceProducer
.struct NIOAsyncWriter<Element, Delegate>
A
NIOAsyncWriter
is a type used to bridge elements from the Swift Concurrency domain into a synchronous world. TheTask
s that are yielding to theNIOAsyncWriter
are the producers. Whereas theNIOAsyncWriterSinkDelegate
is the consumer.protocol NIOAsyncWriterSinkDelegate
The delegate of the
NIOAsyncWriter
. It is the consumer of the yielded writes to theNIOAsyncWriter
. Furthermore, the delegate gets informed when theNIOAsyncWriter
terminated.
Time
struct TimeAmount
Represents a time interval.
struct NIODeadline
Represents a point in time.
Circular Buffers
struct CircularBuffer<Element>
An automatically expanding ring buffer implementation backed by a
ContiguousArray
. Even though this implementation will automatically expand if more elements thaninitialCapacity
are stored, it’s advantageous to prevent expansions from happening frequently. Expansions will always force an allocation and a copy to happen.struct MarkedCircularBuffer<Element>
A circular buffer that allows one object at a time to be “marked” and easily identified and retrieved later.
Operating System State
enum System
struct NIONetworkDevice
A representation of a single network device on a system.
class NIONetworkInterface
A representation of a single network interface on a system.
enum SocketAddress
Represent a socket address to which we may want to connect or bind.
enum NIOBSDSocket
struct NIOIPProtocol
In the Internet Protocol version 4 (IPv4) [RFC791] there is a field called “Protocol” to identify the next level protocol. This is an 8 bit field. In Internet Protocol version 6 (IPv6) [RFC8200], this field is called the “Next Header” field.
Implementing Core Abstractions
protocol ChannelCore
The core
Channel
methods that are for internal use of theChannel
implementation only.protocol ChannelInvoker
A protocol that signals that outbound and inbound events are triggered by this invoker.
protocol ChannelInboundInvoker
Fire inbound events related to a
Channel
through theChannelPipeline
until its end is reached or it’s consumed by aChannelHandler
.protocol ChannelOutboundInvoker
Allows users to invoke an “outbound” operation related to a
Channel
that will flow through theChannelPipeline
until it will finally be executed by the theChannelCore
implementation.
Sendable Helpers
Error Types
enum ByteToMessageDecoderError
Common errors thrown by
ByteToMessageDecoder
s.enum ChannelError
An error that can occur on
Channel
operations.enum ChannelPipelineError
Error
that is used by theChannelPipeline
to inform the user of an error.enum DatagramChannelError
enum EventLoopError
Different
Error
s that are specific toEventLoop
operations / implementations.struct IOError
An
Error
for an IO operation.struct NIOAsyncWriterError
Errors thrown by the
NIOAsyncWriter
.struct NIOAttemptedToRemoveHandlerMultipleTimesError
The removal of a
ChannelHandler
usingChannelPipeline.removeHandler
has been attempted more than once.struct NIOMulticastNotImplementedError
Multicast has not been properly implemented on this channel.
struct NIOMulticastNotSupportedError
Multicast is not supported on this interface.
struct NIOTooManyBytesError
An error that is thrown when the number of bytes in an AsyncSequence exceeds the limit.
enum SocketAddressError
Special
Error
that may be thrown if we fail to create aSocketAddress
.
Uncategorized
Protocols
protocol NIOBinaryIntegerEncodingStrategy
Describes a way to encode and decode an integer as bytes. For more information, see Writing length-prefixed data in ByteBuffer
protocol NIOSerialEventLoopExecutor
A helper protocol that can be mixed in to a NIO
EventLoop
to provide an automatic conformance toSerialExecutor
.
Show implementation details (4)
Hide implementation details
protocol _ChannelInboundHandler
Untyped
ChannelHandler
which handles inbound I/O events.protocol _ChannelOutboundHandler
Untyped
ChannelHandler
which handles outbound I/O events or intercept an outbound I/O operation.protocol _EmittingChannelHandler
ChannelHandler which will emit data by calling
ChannelHandlerContext.write
.protocol _NIOPreconcurrencySendable
Types
struct NIOAsyncChannel<Inbound, Outbound>
Wraps a NIO
Channel
object into a form suitable for use in Swift Concurrency.struct NIOAsyncChannelInboundStream<Inbound>
The inbound message asynchronous sequence of a
NIOAsyncChannel
.struct NIOAsyncChannelOutboundWriter<OutboundOut>
A
NIOAsyncChannelOutboundWriter
is used to write and flush new outbound messages in a channel.enum NIOSingletons
SwiftNIO provided singleton resources for programs & libraries that don’t need full control over all operating system resources. This type holds sizing (how many loops/threads) suggestions.
Show implementation details (1)
Hide implementation details
struct _NIOEventLoopFutureIdentifier
An opaque identifier for a specific
EventLoopFuture
.
Typealiases
Other modules
CNIOAtomics
CNIODarwin
CNIOLLHTTP
CNIOLinux
CNIOSHA1
CNIOWASI
CNIOWindows
NIO
Event-driven, non-blocking, network application framework for high performance protocol servers & clients.
NIOConcurrencyHelpers
NIOEmbedded
NIOFileSystem
NIOFoundationCompat
NIOHTTP1
NIOPosix
NIOTLS
NIOTestUtils
NIOWebSocket
_NIOBase64
_NIOConcurrency
_NIODataStructures
_NIOFileSystem
A file system library for Swift.
_NIOFileSystemFoundationCompat