-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy path1.swift
107 lines (88 loc) · 2.43 KB
/
1.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import FlyingFox
import Foundation
struct PayloadContent: Codable {
let value: Int
init(value: Int){
self.value = value;
}
}
class DummyServer {
let server : HTTPServer
private func handleRequest(request: HTTPRequest) async -> HTTPResponse{
do {
let bodyStr = try await request.bodyData
let body = try JSONDecoder().decode(PayloadContent.self, from: bodyStr)
let response = "\(body.value)"
if let responseData = response.data(using: .utf8) {
return HTTPResponse(statusCode: .ok, body: responseData)
}
} catch {
print("An unexpected error occurred: \(error)")
}
return HTTPResponse(statusCode: .internalServerError, body: Data("Internal Server Error".utf8))
}
init(_ port: UInt16) async {
server = HTTPServer(port: port)
await server.appendRoute("POST /api") {request in
return await self.handleRequest(request: request)
}
}
func start() async throws {
try await server.start()
}
func stop() async throws{
await server.stop(timeout: 3)
}
}
func send(url: URL, value: Int) async -> Int {
let payload = PayloadContent(value: value)
guard let jsonData = try? JSONEncoder().encode(payload) else { return 0 }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
do {
let (data, _) = try await URLSession.shared.data(for: request)
if let responseStr = String(data: data, encoding: .utf8), let intValue = Int(responseStr) {
return intValue
}
} catch {
print(error)
}
return 0
}
func main()async throws{
print("Hello world!")
// Command line arguments
let args = CommandLine.arguments
var n = 10
if args.count == 2, let inputNumber = Int(args[1]) {
n = inputNumber
}
print(n)
// Generate a random port number in the range 20000 to 50000
let port = UInt16.random(in: 20000...50000)
let task = Task {
let server = await DummyServer(port)
try await server.start()
}
let urlString = "http://localhost:\(port)/api"
guard let url = URL(string: urlString) else {
print("Invalid URL")
exit(1)
}
var sum = 0
await withTaskGroup(of: Int.self) { group in
for i in 1...n {
group.addTask {
await send(url: url, value: i)
}
}
for await result in group {
sum += result
}
}
print(sum)
task.cancel()
}
try await main()