Upgrade to Pro — share decks privately, control downloads, hide ads and more …

FrenchKit - Swift Superpowers #2

FrenchKit - Swift Superpowers #2

What swift can offer outside of Apple platforms?

This part is about swift NIO and code sharing between platforms.

David Bonnet

October 08, 2019
Tweet

More Decks by David Bonnet

Other Decks in Programming

Transcript

  1. using vapor 3 // GET /talks func getAll(_ req: Request)

    throws -> Future<[Talk]> { return Talk.query(on: req).all() } swift-NIO
  2. using vapor 3 // GET /talks func getAll(_ req: Request)

    throws -> Future<[Talk]> { return Talk.query(on: req).all() } swift-NIO
  3. using vapor 3 // GET /talks func getAll(_ req: Request)

    throws -> Future<[Talk]> { return Talk.query(on: req).all() } swift-NIO used on database events handling and querying
  4. using vapor 3 // GET /talks func getAll(_ req: Request)

    throws -> Future<[Talk]> { return Talk.query(on: req).all() } swift-NIO used on database events handling and querying dotSwift 2019 Implementing JSON-RPC with swift NIO by Tom Doron (Apple) http tcp udp http/2 BoringSSL
  5. share network code between your client & server you can

    ! network is a thing already! Could we do more?
  6. //Create the run loop let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer

    { try! group.syncShutdownGracefully() } //Bootstrap a connexion let bootstrap = ClientBootstrap(group: group) .channelInitializer { channel in channel.pipeline.addHTTPClientHandlers( position: .first, leftOverBytesStrategy: .fireError ).flatMap { channel.pipeline.addHandler(HTTPFrenchKitHandler()) } } //Connect and wait let channel = try bootstrap.connect(host: "httpbin.org", port: "443") try channel.closeFuture.wait() swift-NIO http client https://github.com/apple/swift-nio/blob/master/Sources/NIOHTTP1Client/main.swift
  7. private final class HTTPFrenchKitHandler: ChannelInboundHandler { public typealias InboundIn =

    HTTPClientResponsePart public typealias OutboundOut = HTTPClientRequestPart public func channelActive(context: ChannelHandlerContext) { // We are connected. var headers = HTTPHeaders() headers.add(name: "Accept", value: "application/json") let version = HTTPVersion(major: 1, minor: 1) let requestHead = HTTPRequestHead(version: version, method: .GET, uri: "/get", headers: headers) context.write(self.wrapOutboundOut(.head(requestHead)), promise: nil) context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) } swift-NIO http client https://github.com/apple/swift-nio/blob/master/Sources/NIOHTTP1Client/main.swift
  8. //Handle received data public func channelRead(context: ChannelHandlerContext, data: NIOAny) {

    let clientResponse = self.unwrapInboundIn(data) switch clientResponse { case .head(let responseHead): print("Received status: \(responseHead.status)") case .body(var byteBuffer): break //Handle body when needed case .end: context.close(promise: nil) //Close channel } } //Handle errors public func errorCaught(context: ChannelHandlerContext, error: Error) { print("error: ", error) context.close(promise: nil) } swift-NIO http client https://github.com/apple/swift-nio/blob/master/Sources/NIOHTTP1Client/main.swift
  9. %

  10. import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif let url =

    URL(string: "https://httpbin.org/get")! let session = URLSession(configuration: .default) let task = session.dataTask(with: url) { data, _, _ in guard let data = data, let response = String(data: data, encoding: .utf8) else { return } print(response) } task.resume() Foundation Networking
  11. import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif let url =

    URL(string: "https://httpbin.org/get")! let session = URLSession(configuration: .default) let task = session.dataTask(with: url) { data, _, _ in guard let data = data, let response = String(data: data, encoding: .utf8) else { return } print(response) } task.resume() Foundation Networking https://forums.swift.org/t/foundationnetworking/24769
  12. &

  13. & '

  14. & '

  15. Wanna try? there is a classroom for that : please

    come and say hi David Bonnet - @iGranDav