4

我正在尝试制作一个简单的回显 UDP 服务器,它发送回所有以 UTF8 字符串为前缀的传入数据报。

在我试图达到这个目标的过程中,我成功地发回了传入的数据,但是当我尝试在这个数据前加上字符串:"You sent: "时,我得到了一个错误writeDataUnsupported

这是我的代码:

我做了一个ChannelInboundHandler调用Echo,它所做的只是:对于每个传入的数据报,它先发送字符串"You sent: ",然后再发送传入数据报的数据。

final class Echo: ChannelInboundHandler {
    typealias   InboundIn = ByteBuffer
    typealias OutboundOut = ByteBuffer

    var wroteResponse = false
    static let response = "You sent: ".data(using: .utf8)!

    func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
        if !wroteResponse {
            var buffer = ctx.channel.allocator.buffer(capacity: Echo.response.count)
            buffer.write(bytes: Echo.response)
            ctx.write(self.wrapOutboundOut(buffer), promise: nil)
            wroteResponse = true
        }
        ctx.write(data, promise: nil)
    }

    func channelReadComplete(ctx: ChannelHandlerContext) {
        ctx.flush()
        wroteResponse = false
    }
}

然后我创建了一个单线程事件循环组并为其分配了一个数据报引导程序。然后我将引导程序绑定到端口 4065。

let  = MultiThreadedEventLoopGroup(numThreads: 1)
let bootstrap = DatagramBootstrap(group: )
    .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
    .channelInitializer { $0.pipeline.add(handler: Echo()) }
defer {
    try! .syncShutdownGracefully()
}


try bootstrap
    .bind(host: "127.0.0.1", port: 4065)
    .wait()
    .closeFuture
    .wait()

为什么我writeDataUnsupported在尝试发送字符串时总是得到这个:"You sent: "

4

2 回答 2

2

因为DatagramChannel你需要将你的包装ByteBuffer成一个AddressEnvelope. 这也意味着您的 ChannelInboundHandler 应该在AddressedEnvelope<ByteBuffer>.

于 2018-03-20T19:48:04.730 回答
2

正如 Norman Maurer 建议的那样,要对 进行ChannelInboundHandler操作,您可以重写,使其看起来更像:AddressedEnvelope<ByteBuffer>Echo

final class Echo: ChannelInboundHandler {
    typealias  InboundIn  = AddressedEnvelope<ByteBuffer>
    typealias OutboundOut = AddressedEnvelope<ByteBuffer>

    static let response = "You sent: ".data(using: .utf8)!

    func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
        var incomingEnvelope = unwrapInboundIn(data)
        var buffer = ctx.channel.allocator.buffer(capacity: Echo.response.count + incomingEnvelope.data.readableBytes)
        buffer.write(bytes: Echo.response)
        buffer.write(buffer: &incomingEnvelope.data)

        let envelope = AddressedEnvelope(remoteAddress: incomingEnvelope.remoteAddress, data: buffer)
        ctx.write(wrapOutboundOut(envelope), promise: nil)
    }

    func channelReadComplete(ctx: ChannelHandlerContext) {
        ctx.flush()
    }
}
于 2018-03-21T07:24:36.420 回答