Skip to content

Instantly share code, notes, and snippets.

@samdods
Last active April 10, 2019 11:40
Show Gist options
  • Save samdods/501cdcbdb9e9963cee92278541df6da5 to your computer and use it in GitHub Desktop.
Save samdods/501cdcbdb9e9963cee92278541df6da5 to your computer and use it in GitHub Desktop.
Listening on a socket and waiting for request
while(true) {
// 5: Wait for a request
let fd = accept(sock, nil, nil)
print("Connection made")
guard fd >= 0 else {
print("Can't accept connection")
continue // goes back to waiting
}
// 6: Parse and route the request
guard let request = Request(fd) else {
continue
}
let responseBody: String?
try {
responseBody = routeRequest(request)
} catch {
print(error)
if let (errorBody, statusCode) = handleError(error) {
let response = httpResponse(body: errorBody, status: statusCode)
write(fd, response)
close(fd)
}
continue
}
// 7: Write the response (if any) to the socket
if let responseBody = responseBody {
let response: String = httpResponse(body: responseBody, status: 200)
write(fd, response)
}
// 8: Close the request
close(fd)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment