这是我的用例...我有一个上游服务,该服务通过网络发送我的Netty应用程序数据,并且该数据需要发布到连接到Netty的多个客户端。推送到客户端的数据必须为HTTP“传输编码:分块”。

我找到了ChunkedStream,尽管我可以创建PipedInputStreamPipedOutputStream(连接到PipedInputStream),然后将ChunkedStream写入通道。然后,当从上游服务接收到数据时,我可以将数据写入通道的PipedOutputStream中并将其发送给客户端:

在频道中已连接

PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
ctx.getChannel().write( new PersistentChunkedStream(in) );

单独的线程将数据发布到连接的通道
ChannelBuffer buff = ChannelBuffers.copiedBuffer("FOO",CharsetUtil.UTF_8);
out.write( buff.array() );
channel.get(ChunkedWriteHandler.class).resumeTransfer();

如果有0字节可用,我必须扩展ChunkedStream以从null返回nextChunk(“挂起”写操作而不挂起线程),因此我在写入关联通道的resumeTransfer后调用PipedOutputStream。当我调试并逐步执行代码时,可以看到正在调用的flushChunkedWriteHandler确实会调用:
Channels.write(ctx, writeFuture, chunk, currentEvent.getRemoteAddress());

加上我写入PipedOutputStream,的字节,但客户端从未收到过。

HTTP curl
~ $ curl -vN http://localhost:8080/stream
* About to connect() to localhost port 8080 (#0)
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /stream HTTP/1.1
> User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
<
### NOTE: NO "FOO" TRANSMIT BACK ###

有什么想法吗?也许有更好的方法可以做到这一点?

最佳答案

我不知道您为什么还要使用PipedInputStream / PipedOutputStream。我认为直接调用Channel.write(..)而不使用您的数据将更加干净/容易。请注意,要在Channel.write(..)中提交尽可能多的数据,这是一项昂贵的操作。

您可以从所需的任何线程调用Channel.write(..),因为它是线程安全的。

07-24 19:40