Skip to content

Instantly share code, notes, and snippets.

@mactkg
Created March 5, 2024 05:34
Show Gist options
  • Save mactkg/611d272666d1c5ad976f48da1a3bcd14 to your computer and use it in GitHub Desktop.
Save mactkg/611d272666d1c5ad976f48da1a3bcd14 to your computer and use it in GitHub Desktop.
Minimum swift hello world server
import Network
let myQueue = DispatchQueue(label: "HTTPSimpleServer")
let listener = try! NWListener(using: .tcp, on: 9000)
listener.newConnectionHandler = { ev in
print("=== new connection ===")
ev.start(queue: myQueue)
ev.receive(minimumIncompleteLength: 0, maximumLength: 8096) { content, contentContext, isComplete, error in
print("=== message recieved ===")
guard let content else { return }
guard let parsed = String(data: content, encoding: .utf8) else {
print("parse error")
return
}
print(parsed)
let response = """
HTTP/1.1 200 OK
Hello
"""
ev.send(content: response.data(using: .utf8), completion: .contentProcessed({ err in
ev.cancel()
print("=== connection canceled ===")
}))
}
}
print("Start listening server at http://localhost:9000")
listener.start(queue: myQueue)
print("send return to leave...")
let _ = readLine()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment