我刚开始使用 SwiftNIO,并在第一次尝试时使用了此代码:
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let bootstrap = ClientBootstrap(group: group)
// Enable SO_REUSEADDR.
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
defer {
try? group.syncShutdownGracefully()
}
do {
let channel = try bootstrap.connect(host: "127.0.0.1", port: 1234).wait()
try channel.closeFuture.wait()
} catch let error {
print(error)
}
它有效,我打印了一个错误,因为我的服务器没有运行。
但是,如果我将该代码带到课程中,则不会发生任何事情:
class Client {
let bootstrap: ClientBootstrap
init() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
self.bootstrap = ClientBootstrap(group: group)
// Enable SO_REUSEADDR.
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
defer {
try? group.syncShutdownGracefully()
}
}
func connect(host: String, port: Int) throws {
let channel = try self.bootstrap.connect(host: host, port: port).wait()
try channel.closeFuture.wait()
}
}
let client = Client()
do {
try client.connect(host: "127.0.0.1", port: 1234)
} catch let error {
print(error)
}
我究竟做错了什么?