Hands-On Server-Side Web Development with Swift
上QQ阅读APP看书,第一时间看更新

SwiftNIO

It is worth mentioning SwiftNIO here, together with other Swift technologies. Apple's SwiftNIO is an open source server-side kernel that provides low-level networking support to the high-level event-driven network application framework. Even though SwiftNIO is not part of open source Swift, this server-side kernel is the fundamental building block for Swift server-side frameworks such as Vapor 3.0. Support for SwiftNIO was also added to Kitura 2.5 in August 2018.

SwiftNIO targets high-performance protocol servers and clients with Netty-like event loops and asynchronous non-blocking calls. The rationale for SwiftNIO is that using the thread-per-connection model of concurrency for low-utilization connections in any server is highly inefficient. SwiftNIO uses the non-blocking I/O model, so we do not need to wait for data to be sent from the network or received from it. The kernel will notify us when an I/O operation is complete.

Under the hood of SwiftNIO, the event processing for managing the execution of work items is conceptualized into EventLoop, which is similar to a dispatch queue in Swift. There are usually a few event loops per CPU core. Event loops run for the entire lifetime of the application, dispatching events to all the objects they own in a SwiftNIO application. Event loops are grouped into an EventLoopGroup. When an EventLoopGroup receives tasks, it will distribute work around the event loops while ensuring thread safety in doing so.

We usually ask EventLoop to schedule work but the work itself will be done by ChannelHandlers in a Channel. Each file descriptor (socket, file, or pipe) in SwiftNIO is associated with a Channel, which performs operations on top of it. The Channel uses ChannelHandler to process each work item. ChannelHandler can handle either inbound or outbound data traffic or both. A sequence of ChannelHandler objects forms a ChannelPipeline so the data in a channel can be transformed as it passes through each ChannelHandler object in the pipeline.

There are several implementations of Channels in SwiftNIO, which are listed as follows:

  • ServerSocketChannel: A channel for sockets that accepts connections like a server
  • SocketChannel: A channel for TCP connections
  • DatagramChannel: A channel for UDP sockets
  • EmbeddedChannel: A channel for testing purposes

In a summary, SwiftNIO implements basic I/O primitives and protocols at low levels of abstraction. It is narrowly focused on providing a powerful building block for high-level networked applications.