Created
May 14, 2020 14:43
-
-
Save yllan/ddeb1b7d545e4c7225816857c48d656c to your computer and use it in GitHub Desktop.
ShitWeb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// ShitWeb | |
// | |
// Created by Yung-Luen Lan on 2020/5/14. | |
// Copyright © 2020 Yung-Luen Lan. All rights reserved. | |
// | |
import Foundation | |
import Network | |
let content = "<html><marquee>Shit Web!</marquee></html>" | |
func response(content: String, connection: NWConnection) { | |
let header = | |
""" | |
HTTP/1.1 200 OK\r | |
Connection: Closed\r | |
Content-Length: \(content.data(using: .utf8)!.count)\r | |
\r\n | |
""" | |
connection.send(content: header.data(using: .utf8), completion: .idempotent) | |
connection.send(content: content.data(using: .utf8), completion: .idempotent) | |
} | |
func readRequest(prevData: Data, connection: NWConnection) { | |
connection.receive(minimumIncompleteLength: 1, maximumLength: 10) { (data, ctx, isFinished, err) in | |
var totalData = prevData | |
if let data = data { | |
totalData = totalData + data | |
} | |
var seenCR = false | |
// CR, LF | |
var lines: [String] = [] | |
var line = Data() | |
var finished = false | |
for byte in totalData { | |
if (byte == 0x0A && seenCR) { // LF | |
lines.append(String(data: line, encoding: .utf8)!) | |
if (String(data: line, encoding: .utf8)! == "") { | |
finished = true | |
break | |
} | |
line = Data() | |
} else if (byte == 0x0D) { | |
seenCR = true | |
} else { | |
seenCR = false | |
line.append(byte) | |
} | |
} | |
if (!finished) { | |
readRequest(prevData: totalData, connection: connection) | |
} else { | |
print(lines) | |
let tmp = lines[0].split(separator: " ") | |
let method = tmp[0] | |
let path = tmp[1] | |
print("METHOD: \(method), Path: \(path)") | |
response(content: "<html><marquee>You're getting \(path)</marquee></html>", connection: connection) | |
} | |
} | |
} | |
let server = try! NWListener(using: .tcp, on: 45678) | |
server.newConnectionHandler = { connection in | |
connection.start(queue: DispatchQueue.main) | |
readRequest(prevData: Data(), connection: connection) | |
// response(content: "<html></html>", connection: connection) | |
} | |
server.start(queue: DispatchQueue.main) | |
print("Start server!") | |
dispatchMain() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment