Allow NIOEchoClient to receive fragmented echo responses. (#2041)

* Add buffering for reading data

* Simplify channelRead in NIOEchoClient

* Remove spacing
This commit is contained in:
Sebastian Vogt 2022-02-07 10:35:16 +01:00 committed by GitHub
parent 4f2c6a3e0b
commit a4ad5eb54d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 9 additions and 7 deletions

View File

@ -20,23 +20,25 @@ let line = readLine(strippingNewline: true)!
private final class EchoHandler: ChannelInboundHandler {
public typealias InboundIn = ByteBuffer
public typealias OutboundOut = ByteBuffer
private var numBytes = 0
private var sendBytes = 0
private var receiveBuffer: ByteBuffer = ByteBuffer()
public func channelActive(context: ChannelHandlerContext) {
print("Client connected to \(context.remoteAddress!)")
// We are connected. It's time to send the message to the server to initialize the ping-pong sequence.
let buffer = context.channel.allocator.buffer(string: line)
self.numBytes = buffer.readableBytes
self.sendBytes = buffer.readableBytes
context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil)
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let byteBuffer = self.unwrapInboundIn(data)
self.numBytes -= byteBuffer.readableBytes
if self.numBytes == 0 {
let string = String(buffer: byteBuffer)
var unwrappedInboundData = self.unwrapInboundIn(data)
self.sendBytes -= unwrappedInboundData.readableBytes
receiveBuffer.writeBuffer(&unwrappedInboundData)
if self.sendBytes == 0 {
let string = String(buffer: receiveBuffer)
print("Received: '\(string)' back from the server, closing channel.")
context.close(promise: nil)
}