Skip to content

Instantly share code, notes, and snippets.

@Dev1an
Last active May 23, 2018 09:38
Show Gist options
  • Select an option

  • Save Dev1an/f6ae38709a2e962e17cffd2b0448cf56 to your computer and use it in GitHub Desktop.

Select an option

Save Dev1an/f6ae38709a2e962e17cffd2b0448cf56 to your computer and use it in GitHub Desktop.
NIO UDP echo server.swift

Unable to run in macOS target

Apparently the problem is caused by not having clang modules enabled for the C targets. To enable them go to your Xcode project and in all the C targets (the NIO ones start with a C like CAtomics), change the Enable Modules (C and Objective-C) to YES.

Xcode settings

And add the following import paths: -Xcc -fmodule-map-file=$(SRCROOT)/Protocol/Atem.xcodeproj/GeneratedModuleMap/CNIOAtomics/module.modulemap -Xcc -fmodule-map-file=$(SRCROOT)/Protocol/Atem.xcodeproj/GeneratedModuleMap/CNIOLinux/module.modulemap -Xcc Β -fmodule-map-file=$(SRCROOT)/Protocol/Atem.xcodeproj/GeneratedModuleMap/CNIODarwin/module.modulemap

You probably want to use an .xcconfig file to do that automatically. swift package generate-xcodeproj --xcconfig-overrides path/to/your/.xcconfig

import Foundation
import NIO
final class Echo: ChannelInboundHandler {
typealias InboundIn = AddressedEnvelope<ByteBuffer>
typealias OutboundOut = AddressedEnvelope<ByteBuffer>
static let response = "You sent: ".data(using: .utf8)!
func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
var incomingEnvelope = unwrapInboundIn(data)
var buffer = ctx.channel.allocator.buffer(capacity: Echo.response.count + incomingEnvelope.data.readableBytes)
buffer.write(bytes: Echo.response)
buffer.write(buffer: &incomingEnvelope.data)
let envelope = AddressedEnvelope(remoteAddress: incomingEnvelope.remoteAddress, data: buffer)
ctx.write(wrapOutboundOut(envelope), promise: nil)
}
func channelReadComplete(ctx: ChannelHandlerContext) {
ctx.flush()
}
}
let πŸ”‚ = MultiThreadedEventLoopGroup(numThreads: 1)
let bootstrap = DatagramBootstrap(group: πŸ”‚)
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.channelInitializer { $0.pipeline.add(handler: Echo()) }
defer {
try! πŸ”‚.syncShutdownGracefully()
}
try bootstrap
.bind(host: "127.0.0.1", port: 4065)
.wait()
.closeFuture
.wait()
import PackageDescription
let package = Package(
name: "NIO UDP Echo server",
dependencies: [
.package(url: "https://github.com/apple/swift-nio.git",
from: "1.1.0"),
],
targets: [
.target(name: "NIO UDP Echo server",
dependencies: [
"NIO"
]
)
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment