BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Apple Open Source SwiftNIO, a Low-Level Non-Blocking I/O Framework for Swift

Apple Open Source SwiftNIO, a Low-Level Non-Blocking I/O Framework for Swift

This item in japanese

At the recent try! Swift Conference in Tokyo, Apple announced the SwiftNIO project, a Netty-like non-blocking cross-platform I/O framework written in Swift.

SwiftNIO aims to be an asynchronous event-driven network framework for the development of high-performance servers and clients. It is currently developed and tested on macOS (10.12+) and Linux (Ubuntu 14.04). According to Apple:

SwiftNIO is a cross-platform asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients.

SwiftNIO aims to be a low-level tool to build networked applications and frameworks, focusing on providing low-overhead I/O primitives and protocol implementations. Accordingly, SwiftNIO can mostly be seen as a building block for higher-level networking communication frameworks that applications will use, or as an high-performance framework that applications with very demanding requirements can use directly. As a consequence of this approach, support for most networking protocols is implemented out-of-tree. According to Cory Benfield, one of the Apple engineers behind SwiftNIO, while the HTTP/1.1 protocol support is in tree, TLS support, Websocket, and HTTP/2 support is out-of-tree.

The basic abstraction provided by SwiftNIO is EventLoop: an object that waits for events and fires some callback when they happen. Ideally, you will have one or two event loops per core. To help with distributing the load across event loops, you can use an EventLoopGroup. On top of EventLoops sit Channels and ChannelPipelines, which provide a friendlier way to be notified on an incoming event associated to a given file descriptor and to dispatch work to process it.

ChannelHandlers provide the steps that a pipeline executes sequentially to handle an event. All handlers are executed on the same thread to make their implementation simpler by not requiring synchronization. This also means handlers cannot block. The highest-level abstraction that SwiftNIO provides is Bootstrap, which streamlines the creation of channels for specific use cases, such as a ServerBootstrap, a ClientBootstrap, and a DatagramBootstrap. You can find all the details in the official documentation.

You can include SwiftNIO into your own project by adding the following dependency to your Package.swift:

dependencies: [
    .package(url: "https://github.com/apple/swift-nio.git", from: "1.0.0")
]

Additionally, you can find two sample apps, NIOChat and NIOEcho, in SwiftNIO repo that demonstrate how you can use the framework.

Rate this Article

Adoption
Style

BT