blob: e508285fb125854eb7f3c2499e7ebc39c12a1554 (
plain)
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
|
//
// gopherClient.swift
//
//
// Created by Navan Chauhan on 12/12/23.
//
import Foundation
import NIO
public class GopherClient {
private let group: EventLoopGroup
public init() {
self.group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
}
deinit {
try? group.syncShutdownGracefully()
}
public func sendRequest(to host: String, port: Int = 70, message: String, completion: @escaping (Result<[gopherItem], Error>) -> Void) {
let bootstrap = ClientBootstrap(group: group)
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.channelInitializer { channel in
channel.pipeline.addHandler(GopherRequestResponseHandler(message: message, completion: completion))
}
bootstrap.connect(host: host, port: port).whenComplete { result in
switch result {
case .success(let channel):
channel.closeFuture.whenComplete { _ in
print("Connection closed")
}
case .failure(let error):
completion(.failure(error))
}
}
}
private func shutdownEventLoopGroup() {
do {
try group.syncShutdownGracefully()
} catch {
print("Error shutting down event loop group: \(error)")
}
}
}
|