Monday, May 20, 2024
HomeiOS DevelopmentSwiftNIO tutorial - The echo server

SwiftNIO tutorial – The echo server

Intoducing SwiftNIO

When you used a excessive stage internet framework, reminiscent of Vapor, up to now, you would possibly had some interplay with occasion loops or guarantees. Properly, these elementary constructing blocks are a part of a low stage community framework, referred to as SwiftNIO, which I will discuss on this tutorial.

Don’t fret if you have not heard about occasion loops or non-blocking IO simply but, I am going to attempt to clarify all the things on this information, so hopefully you will perceive all the things even if you’re a whole newbie to this subject. Let’s begin with some fundamentals about networks and computer systems.

Let’s discuss TCP/IP

It began on January 1st, 1983. The web was born (as some say) and other people began to formally use the web protocol suite (TCP/IP) to speak between gadgets. If you do not know a lot about TCP/IP and you’re curious concerning the underlying components, you’ll be able to learn a couple of different articles, however in a nutshell this mannequin permits us to speak with distant computer systems simply. 💬

For instance that you’ve got two machines, linked by the community. How do they convey with one another? Properly, similar to whenever you ship an everyday letter, first you must specify the deal with of the recipient. In an effort to ship a message to a different laptop, you must know its digital deal with too. This digital deal with known as IP deal with and it appears like this:

So you’ve got bought the deal with, however generally this isn’t sufficient, as a result of a constructing can have a number of flats and you must specify the precise letterbox in an effort to attain the precise particular person. This may occur with computer systems too, the letterbox known as port quantity and the complete deal with of the goal will be created by combining the IP deal with and the port quantity (we name this full deal with as a community socket deal with or just socket, e.g. 💌

After you’ve got specified the precise deal with, you will want somebody to really ship the letter containing your message. The postal supply service can switch your letter, there are two methods to ship it over to the recipient. The primary resolution is to easily ship it with out understanding a lot concerning the supply standing, the digital model of this strategy known as Consumer Datagram Protocol (UDP).

The opposite (extra dependable) technique is to get a receipt concerning the supply, this fashion you’ll be able to ensure that the letter truly arrived and the recipient bought it. Though, the postman can open your letter and alter your message, however it’ll be nonetheless delivered and you will get a notification about this. Once you talk by the community, this technique known as Transmission Management Protocol (TCP).

Okay, that is greater than sufficient community idea, I do know it is a excessive stage abstraction and never solely correct, however hopefully you will get the fundamental concept. Now let’s discuss what occurs contained in the machine and the way we are able to place an precise digital letterbox in entrance of the imaginary home. 📪

The fundamental constructing blocks of SwiftNIO

What do you do in the event you count on a letter? Other than the thrill, most individuals continually verify their mailboxes to see if it is already there or not. They’re listening for the noises of the postman, similar to laptop packages hear on a given port to verify if some information arrived or not. 🤓

What occurs if a letter arrives? Initially you must go and get it out from the mailbox. In an effort to get it you must stroll by the hallway or down the steps or you’ll be able to ask another person to ship the letter for you. Anyway, ought to get the letter by some means first, then primarily based on the envelope you’ll be able to carry out an motion. If it appears like a spam, you will throw it away, but when it is an vital letter you will most certainly open it, learn the contents and ship again a solution as quickly as doable. Let’s keep on with this analogy, and let me clarify this once more, however this time utilizing SwiftNIO phrases.


A Channel connects the underlying community socket with the applying’s code. The channel’s duty is to deal with inbound and outbound occasions, occurring by the socket (or file descriptor). In different phrases, it is the channel that connects the mailbox with you, it’s best to think about it because the hallway to the mailbox, actually the messages are going journey to you by way of a channel. 📨


The ChannelPipeline describes a set of actions about learn how to deal with the letters. One doable model is to decide primarily based on the envelope, you will throw it away if it appears like a spam, or open it if it appears like a proper letter, it is also an motion in the event you reply to the letter. Actions are referred to as as channel handlers in SwiftNIO. Briefly: a pipeline is a predefined sequence of handlers.


The ChannelHandler is the motion that you may carry out whenever you open the letter. The channel handler has an enter and an output kind, which you should use to learn the message utilizing the enter and reply to it utilizing the output. Okay, simply two extra vital phrases, bear with me for a second, I will present you some actual examples afterwards. 🐻


The EventLoop works similar to a run loop or a dispatch queue. What does this imply?

The occasion loop is an object that waits for occasions (normally I/O associated occasions, reminiscent of “information obtained”) to occur after which fires some form of callback once they do.

The trendy CPUs have a restricted variety of cores, apps will most certainly affiliate one thread (of execution) per core. Switching between thread contexts can also be inefficient. What occurs when an occasion has to attend for one thing and a thread turns into obtainable for different duties? In SwiftNIO the occasion loop will obtain the incoming message, course of it, and if it has to attend for one thing (like a file or database learn) it will execute another duties within the meantime. When the IO operation finishes it will swap again to the duty and it will name again to your code when it is time. Or one thing like this, however the primary takeaway right here is that your channel handler is at all times going to be related to precisely one occasion loop, this implies actions shall be executed utilizing the identical context.


The EventLoopGroup manages threads and occasion loops. The MultiThreadedEventLoopGroup goes to steadiness out consumer over the obtainable threads (occasion loops) this fashion the applying goes to be environment friendly and each thread will deal with nearly the identical quantity of shoppers.

Different elements

There are another SwiftNIO elements, we may discuss extra about Futures, Guarantees and the ByteBuffer kind, however I suppose this was greater than sufficient idea for now, so I am not going to dive into these form of objects, however spare them for upcoming articles. 😇

Constructing an echo server utilizing SwiftNIO

You can begin by creating a brand new executable Swift package deal, utilizing the Swift Bundle Supervisor. Subsequent you must add SwiftNIO as a package deal dependency contained in the Bundle.swift file.

import PackageDescription

let package deal = Bundle(
    identify: "echo-server",
    platforms: [
    dependencies: [
            url: "",
            from: "2.0.0"
    targets: [
            name: "Server",
            dependencies: [
                    name: "NIO",
                    package: "swift-nio"

The following step is to change the primary undertaking file, we are able to simply create the SwiftNIO primarily based TCP server through the use of the ServerBootstrap object. First we’ve got to instantiate a MultiThreadedEventLoopGroup with a lot of threads, utilizing the CPU cores within the system.

Then we configure the server by including some channel choices. You do not have to know a lot about these simply but, the attention-grabbing half is contained in the childChannelInitializer block. We create the precise channel pipeline there. Our pipeline will include two handlers, the primary one is the built-in BackPressureHandler, the second goes to be our customized made EchoHandler object.

If you’re within the obtainable ChannelOptions, you’ll be able to check out the NIO supply code, it additionally comprises some superb docs about this stuff. The ultimate step is to bind the server bootstrap object to a given host and port, and watch for incoming connections. 🧐

import NIO

public struct Server {
    public static func principal() throws {
        let eventLoopGroup = MultiThreadedEventLoopGroup(
            numberOfThreads: System.coreCount

        defer {
            strive! eventLoopGroup.syncShutdownGracefully()

        let serverBootstrap = ServerBootstrap(
            group: eventLoopGroup
            worth: 256
            worth: 1
        .childChannelInitializer { channel in
            worth: 1
            worth: 16
            worth: AdaptiveRecvByteBufferAllocator()

        let defaultHost = "" 
        let defaultPort = 8888

        let channel = strive serverBootstrap.bind(
            host: defaultHost,
            port: defaultPort

        print("Server began and listening on (channel.localAddress!)")
        strive channel.closeFuture.wait()
        print("Server closed")

As I discussed this, in an effort to deal with an occasion occurring on the channel we’ve got can create a customized ChannelInboundHandler object. Contained in the channelRead operate it’s doable to unwrap the inbound information right into a ByteBuffer object and write the enter message onto the output as a wrapped NIOAny object.

Problem: write a server that may print colourful messages. Trace: constructing a textual content modifying server.

import NIO

ultimate class EchoHandler: ChannelInboundHandler {

    typealias InboundIn = ByteBuffer
    typealias OutboundOut = ByteBuffer

    func channelRead(
        context: ChannelHandlerContext,
        information: NIOAny
    ) {
        let enter = self.unwrapInboundIn(information)
            let message = enter.getString(at: 0, size: enter.readableBytes)
        else {
        var buff = message.rely)
        context.write(wrapOutboundOut(buff), promise: nil)

    func channelReadComplete(
        context: ChannelHandlerContext
    ) {

    func errorCaught(
        context: ChannelHandlerContext,
        error: Error
    ) {

        context.shut(promise: nil)

When you run the app and hook up with it utilizing the telnet 8888 command you’ll be able to enter some textual content and the server will echo it again to you. Take into account that this can be a quite simple TCP server, with out HTTP, however it’s doable to jot down express-like HTTP servers, JSON API servers, even a sport backend and lots of different cool and loopy performant stuff utilizing SwiftNIO. I hope this tutorial will enable you to get began with SwiftNIO, I am additionally studying quite a bit concerning the framework currently, so please forgive me (and even appropriate me) if I missed / tousled one thing. 😅

So once more: SwiftNIO a (low-level) non-blocking event-driven community utility framework for prime efficiency protocol servers & shoppers. It is like Netty, however written for Swift.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments