public final class ServerBootstrap

A ServerBootstrap is an easy way to bootstrap a ServerSocketChannel when creating network servers.


    let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
    defer {
        try! group.syncShutdownGracefully()
    let bootstrap = ServerBootstrap(group: group)
        // Specify backlog and enable SO_REUSEADDR for the server itself
        .serverChannelOption(ChannelOptions.backlog, value: 256)
        .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)

        // Set the handlers that are applied to the accepted child `Channel`s.
        .childChannelInitializer { channel in
            // Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline.
            channel.pipeline.addHandler(BackPressureHandler()).flatMap { () in
                // make sure to instantiate your `ChannelHandlers` inside of
                // the closure as it will be invoked once per connection.

        // Enable SO_REUSEADDR for the accepted Channels
        .childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
        .childChannelOption(ChannelOptions.maxMessagesPerRead, value: 16)
        .childChannelOption(ChannelOptions.recvAllocator, value: AdaptiveRecvByteBufferAllocator())
    let channel = try! bootstrap.bind(host: host, port: port).wait()
    /* the server will now be accepting connections */

    try! channel.closeFuture.wait() // wait forever as we never close the Channel

The EventLoopFuture returned by bind will fire with a ServerSocketChannel. This is the channel that owns the listening socket. Each time it accepts a new connection it will fire a SocketChannel through the ChannelPipeline via fireChannelRead: as a result, the ServerSocketChannel operates on Channels as inbound messages. Outbound messages are not supported on a ServerSocketChannel which means that each write attempt will fail.

Accepted SocketChannels operate on ByteBuffer as inbound data, and IOData as outbound data.