Classes
The following classes are available globally.
-
This class provides an implementation of a buffer that can be added to and taken from in chunks. Data is always added to the end of the buffer (using
BufferList.append(...)
and taken out of the buffer (usingBufferList.fill(...)
) from the beginning towards the end. The location indicating where the next chunk of data will be taken from is maintained, this location can then be reset to enable data to be taken out of the buffer from the beginning again.In the below example, we create an empty
BufferList
instance. You can then append data to yourBufferList
instance, in our casewriteBuffer
. We then make two seperate appends. WhenwriteBuffer
contains the data which you wish to write out you can useBufferList.fill(...)
to write out the data from the buffer to your chosen location, which in this case isfinalArrayOfNumbers
.Usage Example:
See morevar writeBuffer = BufferList() let firstArrayOfNumbers: [UInt8] = [1,2,3,4] // Append a set of data to the 'writeBuffer' object writeBuffer.append(bytes: UnsafePointer<UInt8>(firstArrayOfNumbers), length: MemoryLayout<UInt8>.size * firstArrayOfNumbers.count) // Number of bytes stored in the 'writeBuffer' object print(writeBuffer.count) // Prints "4" let secondArrayOfNumbers: [UInt8] = [5,6,7,8] // Append a second set of data to the 'writeBuffer' object writeBuffer.append(bytes: UnsafePointer<UInt8>(secondArrayOfNumbers), length: MemoryLayout<UInt8>.size * secondArrayOfNumbers.count) print(writeBuffer.count) // Prints "8" let finalArrayOfNumbers: [UInt8] = [0,0,0,0,0,0,0,0,9,10] // Fill the destination buffer 'finalArrayOfNumbers' with the data from 'writeBuffer' let count = writeBuffer.fill(buffer: UnsafeMutableRawPointer(mutating: finalArrayOfNumbers) .assumingMemoryBound(to: UInt8.self), length: ((MemoryLayout<UInt8>.size) * finalArrayOfNumbers.count)) print("count = \(count), buffer is = \(finalArrayOfNumbers)" ) // Prints "count = 8, buffer is = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
Declaration
Swift
public class BufferList
-
This class provides a set of low level APIs for issuing HTTP requests to another server. A new instance of the request can be created, along with options if the user would like to specify certain parameters such as HTTP headers, HTTP methods, host names, and SSL credentials.
Data
andString
objects can be added to aClientRequest
too, and URLs can be parsed.Usage Example:
See more//Function to create a new `ClientRequest` using a URL. public static func request(_ url: String, callback: @escaping ClientRequest.Callback) -> ClientRequest { return ClientRequest(url: url, callback: callback) } //Create a new `ClientRequest` using a URL. let request = HTTP.request("http://localhost/8080") {response in ... }
Declaration
Swift
public class ClientRequest
-
This class describes the response sent by the remote server to an HTTP request sent using the
ClientRequest
class. Data or Strings can be read in, and URLs can be parsed.Usage Example:
See more//The `ClientResponse` object that describes the response that was received from the remote server is used in a callback. public typealias Callback = (ClientResponse?) -> Void
Declaration
Swift
public class ClientResponse
-
The “root” class for the FastCGI server implementation. A
FastCGIServer
instance can be created.Usage Example:
See more//Implement a `FastCGI` server. let server = FastCGI.createServer()
Declaration
Swift
public class FastCGI
-
A server that listens for incoming HTTP requests that are sent using the FastCGI protocol. This can be used to create a new
FastCGIServer
and have it listen for conenctions and handle a new client FastCGI request.Usage Example:
See more//Create a `FastCGI` server on a specified port. let server = try FastCGIServer.listen(on: port, delegate: delegate)
Declaration
Swift
public class FastCGIServer : Server
-
The FastCGIServerRequest class implements the
ServerRequest
protocol for incoming HTTP requests that come in over a FastCGI connection. This can be used to read data from the body of the request and process the original request URI.Usage Example:
See more//Create a `FastCGIServerRequest` to handle a new client FastCGI request. let request = FastCGIServerRequest(socket: clientSocket) //Handle a new client FastCGI request. request.parse() { status in switch status { case .success: ... break case .unsupportedRole: ... break default: ... break } }
Declaration
Swift
public class FastCGIServerRequest : ServerRequest
-
The FastCGIServerRequest class implements the
ServerResponse
protocol for incoming HTTP requests that come in over a FastCGI connection.Usage Example:
See more//Create a `FastCGIServerResponse` object with socket and request parameters. let response = FastCGIServerResponse(socket: clientSocket, request: request) ... //Set the status code. response.statusCode = HTTPStatusCode.badRequest ... //Write a String to the `FastCGIServerResponse` object. try response.write(from: "Some String") ... //Stop the `FastCGIServerResponse` object. try response.end()
Declaration
Swift
public class FastCGIServerResponse : ServerResponse
-
A set of helpers for HTTP: status codes mapping, server and client request creation.
Usage Example:
See more//Create a HTTP server. let server = HTTP.createServer() //Create a new a `ClientRequest` instance using a URL. let request = HTTP.request("http://localhost/8080") {response in ... } //Get a `ClientRequest` instance from a URL. let getHTTP = HTTP.get("http://localhost/8080") { response in ... } HTTP.escape(url: testString)
Declaration
Swift
public class HTTP
-
An HTTP server that listens for connections on a socket.
Usage Example:
See more//Create a server that listens for connections on a specified socket. let server = try HTTPServer.listen(on: 0, delegate: delegate) ... //Stop the server. server.stop()
Declaration
Swift
public class HTTPServer : Server
-
This class implements the
ServerRequest
protocol for incoming sockets that are communicating via the HTTP protocol. Data and Strings can be read in.Usage Example:
See morefunc handlePost(request: ServerRequest, response: ServerResponse) { var body = Data() do { let length = try request.readAllData(into: &body) let result = "Read \(length) bytes" response.headers["Content-Type"] = ["text/plain"] response.headers["Content-Length"] = ["\(result.count)"] try response.end(text: result) } catch { print("Error reading body or writing response") } }
Declaration
Swift
public class HTTPServerRequest : ServerRequest
-
This class implements the
ServerResponse
protocol for outgoing server responses via the HTTP protocol. Data and Strings can be written.The example below uses this in its
response
parameter, with the example requesting a connection be upgraded and catch any errors that occur.Usage Example:
See morefunc upgradeConnection(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) { guard let protocols = request.headers["Upgrade"] else { do { response.statusCode = HTTPStatusCode.badRequest try response.write(from: "No protocol specified in the Upgrade header") try response.end() } catch { Log.error("Failed to send error response to Upgrade request") } return } }
Declaration
Swift
public class HTTPServerResponse : ServerResponse
-
This class processes the data sent by the client after the data was read. The data is parsed, filling in a
HTTPServerRequest
object. When the parsing is complete, theServerDelegate
is invoked.Usage Example:
See more//Create an `IncomingHTTPSocketProcessor` object. var processor : IncomingHTTPSocketProcessor? //Write from an NSMutableData buffer. processor.write(from: NSMutableData) //Write from a data object. processor.write(from: utf8, length: utf8Length)
Declaration
Swift
public class IncomingHTTPSocketProcessor : IncomingSocketProcessor
-
Splits and parses URLs into components - scheme, host, port, path, query string etc. according to the following format:
scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
Usage Example:
See more// Initialize a new URLParser instance, and check whether or not a connection has been established. let url = "http://user:password@sample.host.com:8080/a/b/c?query=somestring#hash".data(using: .utf8)! let urlParser = URLParser(url: url, isConnect: false)
Declaration
Swift
public class URLParser : CustomStringConvertible
-
A class that abstracts out the HTTP header APIs of the
ServerRequest
andServerResponse
protocols.Usage Example:
See morepublic var headers: HeadersContainer { return httpParser?.headers ?? HeadersContainer() }
Declaration
Swift
public class HeadersContainer
extension HeadersContainer: Collection
-
This class handles incoming sockets to the HTTPServer. The data sent by the client is read and passed to the current
IncomingDataProcessor
.Note
The IncomingDataProcessor can change due to an Upgrade request.
Note
This class uses different underlying technologies depending on:
1. On Linux, if no special compile time options are specified, epoll is used 2. On OSX, DispatchSource is used 3. On Linux, if the compile time option -Xswiftc -DGCD_ASYNCH is specified, DispatchSource is used, as it is used on OSX.
Usage Example:
See morefunc upgrade(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) -> (IncomingSocketProcessor?, Data?, String?) { let (processor, responseText) = upgrade(handler: handler, request: request, response: response) if let responseText = responseText { return (processor, responseText.data(using: .utf8), "text/plain") } return (processor, nil, nil) }
Declaration
Swift
public class IncomingSocketHandler
-
The IncomingSocketManager class is in charge of managing all of the incoming sockets. In particular, it is in charge of:
- On Linux when no special compile options are specified: a. Creating the epoll handle b. Adding new incoming sockets to the epoll descriptor for read events c. Running the “thread” that does the epoll_wait
- Creating and managing the IncomingSocketHandlers and IncomingHTTPDataProcessors (one pair per incomng socket)
- Cleaning up idle sockets, when new incoming sockets arrive.
Usage Example:
See more//Create a manager to manage all of the incoming sockets. var manager: IncomingSocketManager? override func setUp() { manager = IncomingSocketManager() }
Declaration
Swift
public class IncomingSocketManager
-
A class that provides a set of helper functions that enables a caller to wait for a group of listener blocks to finish executing.
Usage Example:
See more//Wait for all of the listeners to stop. ListenerGroup.waitForListeners() //Enqueue a block of code on a given queue, assigning it to the listener group in the process (so we can wait on it later). ListenerGroup.enqueueAsynchronously(on: DispatchQueue.global(), block: queuedBlock)
Declaration
Swift
public class ListenerGroup