SwfitNIO is actually a low-level tool for developing high-performance web applications as an alternative to “one thread per connection.”

To improve performance, SwfitNIO uses non-blocking IO, as its name suggests. Non-blocking IO is very different from blocking IO because the application doesn’t have to wait to send or receive data from the network, and the system kernel notifies SwfitNIO when it has actionable IO.

SwfitNIO does not provide a solution similar to Web frameworks, but rather aims to provide the underlying building blocks for the upper frameworks. When developing Web applications, most developers do not use SwfitNIO directly, choosing one of the many Web frameworks in the Swift ecosystem. However, most of these frameworks use SwfitNIO.

SwfitNIO aims to support all platforms that can run Swift. Currently, SwfitNIO runs on macOS and Linux, including:

  • Ubuntu 14.04 +

  • MacOS 10.12 +

SwfitNIO contains several basic building blocks that make up all SwfitNIO applications.

  • EventLoopGroup

  • EventLoop

  • Channel

  • ChannelHandler

  • Bootstrap

  • ByteBuffer

EventLoop, SwfitNIO’s most basic IO primitive, waits for an event to occur, and when it does, triggers some kind of callback. In most SwfitNIO applications, the number of EventLoop objects is small, usually one or two for each CPU core. In general, EventLoop exists for the entire life cycle of the application for unlimited event distribution.

Eventloops can be combined into EventLoopGroups, which provide a mechanism for distributing workloads between eventloops. For example, when the server listens for external connections, the socket used to listen for connections is registered with an EventLoop. However, we don’t want this EventLoop to bear all the connection load, so we can use the EventLoopGroup to spread the connection load among multiple Eventloops.

At present, SwiftNIO provides a EventLoopGroup implementation (MultiThreadedEventLoopGroup) and two EventLoop implementation (SelectableEventLoop and EmbeddedEventLoop).

MultiThreadedEventLoopGroup creates multiple threads (using POSIX pthreads library), and assign a SelectableEventLoop object for each thread.

SelectableEventLoop uses selectors (based on kQueue or epoll) to manage IO events from files and networks. EmbeddedEventLoop is an empty EventLoop that does nothing and is primarily used for testing.

Despite the importance of EventLoop, most developers don’t interact with it much beyond creating EventLoopPromises and scheduling jobs. Channels and ChannelHandlers are commonly used by developers.

Each file descriptor corresponds to a Channel, which manages the life cycle of the file descriptor and handles events that occur on the file descriptor: EventLoop notifies the Channel whenever it detects an event associated with the corresponding file descriptor.

A ChannelPipeline consists of a series of ChannelHandlers that process events in a Channel in sequence. ChannelPipeline is just like a data processing pipeline, hence the name.

ChannelHandler is either Inbound, Outbound, or both. Inbound’s ChannelHandler handles “Inbound” events, such as reading data from a socket, closing a socket, or other remotely initiated events. The Outbound ChannelHandler handles Outbound events, such as writing data, initiating a connection, and closing the local socket.

ChannelHandler processes events in a certain order, for example, read events pass from the front of the pipe to the back, and write events pass from the back of the pipe to the front. Each ChannelHandler generates a new event for the next ChannelHandler after processing an event.

Channelhandlers are highly reusable components, so they are designed to be as lightweight as possible, handling only one data transformation per ChannelHandler, allowing for flexible combinations of channelHandlers to improve code reusability and encapsulation.

ChannelHandlerContext can be used to track where the ChannelHandler is in the ChannelPipeline. The ChannelHandlerContext contains references from the current ChannelHandler to the previous and next ChannelHandler, so new events can be fired at any time the ChannelHandler is still in the pipeline.

SwiftNIO has multiple ChannelHandlers built in, including an HTTP parser. In addition, SwiftNIO provides some Channel implementations, Examples are ServerSocketChannel (for receiving connections), SocketChannel (for TCP connections), DatagramChannel (for UDP sockets), and EmbeddedChannel (for testing).

SwiftNIO provides several Bootstrap objects to simplify Channel creation. Some Bootstrap objects also provide additional functionality, such as support for Happy Eyeballs.

SwiftNIO currently offers three types of Bootstrap: ServerBootstrap (for listening on channels), ClientBootstrap (for TCP channels), and DatagramBootstrap (for UDP channels).

SwiftNIO provides ByteBuffer, a fast copy-on-write ByteBuffer that is a key building block for most SwiftNIO applications.

ByteBuffer has a number of useful features and “hooks” that you can use in its “unsafe” mode. This approach results in better performance at the cost of memory problems in the application. In general, it is recommended to use ByteBuffer in safe mode.

The main difference between concurrent and synchronous code is that not all actions can be done immediately. For example, when writing data to a Channel, EventLoop might not immediately flush the data onto the network. For this purpose, SwiftNIO provides EventLoopPromise and EventLoopFuture for managing asynchronous operations.

EventLoopFuture is actually a container for the return value of the function at some point in the future. Each EventLoopFuture object has a corresponding EventLoopPromise that holds the actual result. Once the EventLoopPromise executes successfully, the EventLoopFuture is complete.

Polling to check that EventLoopFuture is complete is a very inefficient way to do so, so EventLoopFuture is designed to receive callback functions. That is, the callback is executed when the result is available.

EventLoopFuture handles scheduling and ensures that the callback is executed on the same EventLoop that created the EventLoopPromise in the first place, so there is no need to do any synchronization on the callback.

SwiftNIO aims to be a powerful framework for web application development, but does not want to provide a perfect solution for all levels of abstraction. SwiftNIO focuses on basic IO primitives and low-level protocol implementations, leaving other levels of abstraction to the wider community to build. SwiftNIO will be a building block for server-side applications, but not necessarily a framework for applications to use directly.

Performance-critical applications may use SwiftNIO directly, reducing the overhead of upper-level abstractions. SwiftNIO helps these applications improve performance while reducing maintenance costs. SwiftNIO also provides useful abstractions for certain scenarios that high-performance web servers can use directly.

SwiftNIO’s core repository provides some very important protocol implementations, such as HTTP. However, we believe that the implementation of most protocols should be kept separate from the underlying network stack because their release rhythms are quite different. To this end, we encourage communities to implement and maintain their protocol implementations themselves. In fact, some of the protocol implementations provided by SwiftNIO were originally developed by the community, such as TLS and HTTP/2.

The following projects provide very useful protocol implementation documentation:

swift-nio-ssl:https://github.com/apple/swift-nio-ssl

Swift-nio-http2 (in preparation)

The API documentation:

https://apple.github.io/swift-nio/docs/current/NIO/index.html

There are currently some examples that demonstrate how to use SwiftNIO.

  • Chat client:

    https://github.com/apple/swift-nio/tree/master/Sources/NIOChatClient

  • Chat server:

    https://github.com/apple/swift-nio/tree/master/Sources/NIOChatServer

  • Echo client:

    https://github.com/apple/swift-nio/tree/master/Sources/NIOEchoClient

  • Echo server:

    https://github.com/apple/swift-nio/tree/master/Sources/NIOEchoServer

  • Http server:

    https://github.com/apple/swift-nio/tree/master/Sources/NIOHTTP1Server

SwiftNIO uses SwiftPM as a build tool. To use SwiftNIO in a project, simply add dependencies to package. swift:

Dependencies: [. Package (url: "https://github.com/apple/swift-nio.git", from: "1.0.0")]Copy the code

Then add the corresponding SwiftNIO module to the dependency list.

You can copy the SwiftNIO codebase locally and build it using SwiftPM. For example, compile and run the Echo server with the following command:

swift build
swift test
swift run NIOEchoServerCopy the code

Then verify that the server is running properly via the console:

echo "Hello SwiftNIO" | nc localhost 9999Copy the code

If all is well, you will see a message printed out on the console.

In addition, you can build and run sample code from Docker-compose.

First make sure Docker is installed locally, then switch to the Docker directory and run the following command:

docker-compose up testCopy the code

This command will create a base image that includes Swift 4.0, compile SwiftNIO, and run test cases.

docker-compose up echoCopy the code

This command will create a base image, compile SwiftNIO, and run NIOEchoServer on localhost:9999. Can be achieved by the echo Hellp SwiftNIO | nc localhost 9999 to test it.

docker-compose up httpCopy the code

This command will create a base image, compile SwiftNIO, and run NIOHTTP1Server on localhost:8888. You can test it at curl http://localhost:8888.

https://github.com/apple/swift-nio

Mobile development front

Mobile Frontier is InfoQ’s vertical community focused on mobile development technology. Please email your submission to [email protected], marked “Mobile Development Front Submission”.

Video, 3 d, machine learning, algorithm engineering, IOT, intelligent new proposition is put forward, such as the hardware enriched the contents of the ecology and the content of the form to the stability of the traditional development mode and online has brought new challenges, and open a monster APP move ecological also makes more and more mobile developers begin to surrounding ecological development. QCon Beijing 2018 will select some topics to share with you, including the development experience and ideas of national mini-games like Leapfrog, hoping to enlighten you on the development direction of new mobile technology.

At present, there is a 20% discount for the last week of registration, with an immediate reduction of 1360 yuan. If you have any questions, please feel free to consult Hanna, ticket purchasing manager, tel: 15110019061, wechat: QCON-0410.