SwiftNIO:TCP服务器未发回数据



我已经为SwiftNIO编写了自己的处理程序,但我无法让它发送任何内容。

class MyHandler: ChannelInboundHandler
{
public typealias InboundIn = ByteBuffer
public typealias OutboundOut = ByteBuffer

public func channelRead(context: ChannelHandlerContext, data: NIOAny)
{
let message = "The weather is sunny.n"
let length = message.utf8.count

var buffer = context.channel.allocator.buffer(capacity: length)
buffer.writeString(message)
let out = self.wrapOutboundOut(buffer)
context.write(out, promise: nil)
}

public func channelReadComplete(context: ChannelHandlerContext)
{
context.flush()
}

public func errorCaught(context: ChannelHandlerContext, error: Error)
{
print("error: ", error)
context.close(promise: nil)
}
}

如果我只是将channelRead功能保留为如下,它会成功地回显传入的文本:

public func channelRead(context: ChannelHandlerContext, data: NIOAny)
{
context.write(data, promise: nil)
}

我做错了什么?

您没有做错任何事情,这应该可以正常工作。每次接收到任何数据时,它都会发回The weather is sunny.n

我也试过了,它有效:

$ nc localhost 9999
How's the weather?
The weather is sunny.
How are you?
The weather is sunny.

我使用的完整代码是

import NIO
class MyHandler: ChannelInboundHandler
{
public typealias InboundIn = ByteBuffer
public typealias OutboundOut = ByteBuffer

public func channelRead(context: ChannelHandlerContext, data: NIOAny)
{
let message = "The weather is sunny.n"
let length = message.utf8.count

var buffer = context.channel.allocator.buffer(capacity: length)
buffer.writeString(message)
let out = self.wrapOutboundOut(buffer)
context.write(out, promise: nil)
}

public func channelReadComplete(context: ChannelHandlerContext)
{
context.flush()
}

public func errorCaught(context: ChannelHandlerContext, error: Error)
{
print("error: ", error)
context.close(promise: nil)
}
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
defer {
try! group.syncShutdownGracefully()
}
let bootstrap = ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
channel.pipeline.addHandler(MyHandler())
}
let serverChannel = try bootstrap.bind(host: "localhost", port: 9999).wait()
try serverChannel.closeFuture.wait()

最新更新