Swift is an easy to learn programming language that is becoming increasingly popular. The library’s goal is to provide a lightweight HTTP server for the development of web applications and games.
The cocoahttpserver is a lightweight async HTTP server library, written in pure Swift. It runs on iOS, MacOS and Linux.
In Swift, a super-lightweight async HTTP server.
Please read: iOS UI testing with an embedded web server.
See also: Ambassador, a lightweight web framework built on Embassy.
- Swift 4 and 5 are two versions of Swift.
- iOS, tvOS, MacOS, and Linux are all supported.
- Only 1.5 K lines, thus it’s very light.
- There is no reliance on a third party.
- Long-polling, delay, and bandwidth limiting are all achievable with an async event loop-based HTTP server.
- SWSGI-based HTTP application with a lot of flexibility
- IPV6 capable, although IPV4 is also supported (dual stack)
- Covered by automated testing
The following is a basic illustration of how Embassy operates.
let loop = attempt! SelectorEventLoop(selector: try! ), SelectorEventLoop(selector: try! ), SelectorE let server = DefaultHTTPServer (KqueueSelector()) (eventLoop: loop, port: 8080) in / Start HTTP response (environment: [String: Any], startResponse: ((String, [(String, String)]) -> Void), sendBody: ((Data) -> Void) let pathInfo = environ[“PATH INFO”]! startResponse(“200 OK”, ) as! String sendBody(Data(“the path you’re visiting is (pathInfo.debugDescription)”.utf8)) / send EOF sendBody(Data()) try! server.start(); loop.runForever; server.start(); server.start(); server.start(); server.start(); server ()
Then go to http://[::1]:8080/foo-bar in your browser to check what’s going on.
“/foo-bar” is the route you’re on.
For security concerns, the server is only connected to the localhost interface (::1) by default. If you wish to connect to your server from another computer, set the bind interface to all addresses:
let server = DefaultHTTPServer; DefaultHTTPServer; DefaultHTTPServer; (eventLoop: loop, interface: “::”, port: 8080)
Loop of Async Events
You can obtain the async event loop by looking for the key embassy.event loop in the environment dictionary and casting it to EventLoop. You may make a SWSGI program that delays the sendBody call, for example.
start app = ( environ: [String: Any]) ((String, [(String, String)]) -> Void) in startResponse, sendBody: @escaping ((Data) -> Void) (“200 OK”, ) as loop = environment[“embassy.event loop”] Event Loop loop.call(withDelay: 1) sendBody(Data(“hello “.utf8)) loop.call(withDelay: 2) sendBody(Data(“baby “.utf8)) loop.call(withDelay: 3) sendBody(Data(“fin”.utf8)) sendBody(Data()) loop.call(withDelay: 4) sendBody(Data(“fin”.utf8)) loop.call(with
Please keep in mind that functions provided to SWSGI should only be executed inside the same thread for the EventLoop to run; they are not threadsafe, therefore you shouldn’t utilize GCD to postpone any calls. Instead, you may utilize several methods from EventLoop, which are all threadsafe.
(Void) -> Void) call(Void) call(Void) call(Void) call(Void)
In the event loop, call the specified callback as soon as feasible.
(withDelay: TimeInterval, callback: (Void) -> Void) call(withDelay: TimeInterval, callback: (Void) -> Void) call(withDelay: TimeInter
Call the specified callback withDelay seconds before calling it in the event loop.
(atTime: Date, callback: (Void) -> Void) call(atTime: Date, callback: (Void) -> Void) call(atTime: Date, call
In the event loop, schedule the specified callback to be invoked at atTime. If the provided time is 0 or in the past, this function behaves identically like a call with the exception of the callback argument.
SWSGI (Swift Web Server Gateway Interface) is an acronym for “Swift Web Server Gateway Interface.”
SWSGI is a nod to Python’s WSGI module (Web Server Gateway Interface). It’s a gateway interface that allows web applications to communicate with HTTP clients without having to understand the technical details of the HTTP server.
It’s defined this way:
typealias in the public domain SWSGI = ( [String: Any], SWSGI = ( [String: Any], SWSGI = ( [Str ((String, [(String, String)]) -> Void), @escaping ((String, [(String, String)]) @escaping ((Data) -> Void) -> Void) -> Void) -> Void) -> Void) -> Void) -> Void)
It’s a dictionary that includes all of the information needed to complete the request. It mostly adheres to the WSGI standard, with the exception that wsgi.* keys are replaced with swsgi.*. Consider the following scenario:
[ ] “”SERVER NAME”: “[::1]”, “SERVER PROTOCOL”: “HTTP/1.1”, “SERVER PORT”: “53479”, “REQUEST METHOD”: “GET”, “SCRIPT NAME”: “”, “PATH INFO”: “/”, “HTTP HOST”: “[::1]:8889”, “HTTP USER AGENT”: “Mozilla/5.0 (Mac (KHTML, like Gecko) Chrome/50.0.2661.102 “HTTP ACCEPT LANGUAGE” : “en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4,zh-CN;q=0.2”, “HTTP CONNECTION” : “keep-alive”, “HTTP ACCEPT ENCODING” : “gzip, deflate, sdch”, “swsgi.version” : “0.1”, “HTTP CON “] : false
You may use swsgi.input, for example, to read requests from the body.
environment[“swsgi.input”] let input = as! SWSGIInput data in SWSGIInput data in SWSGIInput data in SWSGIInput data in SWSGIInput data in SWSGIInput data in S
When the EOF is reached, an empty Data is given to the input data handler. Also, if swsgi.input is not set or set to nil, the request body will not be read. Set swsgi.input to nil when you don’t want to receive any data from the client as a bandwidth control.
There are a few additional keys for the Embassy server.
- embassy.connection – The request’s HTTPConnection object
- EventLoop object embassy.event loop
- embassy.version – embassy’s version as a String, for example 3.0.0.
The first parameter is a status code with message, such as “200 OK,” and the function starts sending HTTP response headers to the client. Headers, as a list of key-value tuples, is the second parameter.
You may use the following code to respond to HTTP headers.
[(“Set-Cookie”, “foo=bar”)] startResponse(“200 OK”)] startResponse(“200 OK”) startResponse(“200 OK”) startResponse(“200 OK”) startRe
The startResponse method may only be called once per request; any further calls will be ignored.
This function sends body data to the client. In order to call sendBody, you must first call startResponse. All calls to sendBody will be ignored unless you first call startResponse. Here is where you may submit data.
Simply call sendBody with an empty Data to stop the response data stream.
Add Embassy to your Podfile to install using CocoaPod:
‘Embassy’ pod, ‘> 4.1’
Add Embassy to your Cartfile to install using Carthage:
4.1 github “envoy/Embassy”
Package Manager is a program that allows you to manage
This Embassy repo should be added to Package. swift, similar to this
let package = Package( name: “EmbassyExample”, dependencies: [.package(url: “https://github.com/envoy/Embassy.git”, from: “4.1.1”), ] ) import PackageDescription let package = Package( name: “EmbassyExample”, dependencies: [.package(url: “https://github.com/envoy/Embassy.git”, from:
This sample project may be found here.
The swift web programming is a super lightweight async HTTP server library in pure Swift. It runs on iOS, MacOS and Linux.
- swift rest api server
- swift web server
- https server swift