0

我对在 zeroCopy 操作中使用 Channels.newChannel(OutputStream/InputStream) 有一些疑问。它将作为 zeroCopy 吗?我有一些限制,比如必须发送第一个标题部分(文件和用户相关信息)然后是文件内容。为了测试,我也覆盖了 BufferedOutputStream,但在 fileChannel.transferTo 调用时,它正在调用我的覆盖方法......请帮助我如何在这种情况下实现 zeroCopy(标题+内容)。

部分测试代码:

String host = "127.0.0.1";
SocketAddress sad = new InetSocketAddress(host, ZeroCopyServer.PORT);
Socket s=new Socket();
s.connect(sad);

OutputStream o=s.getOutputStream();
OutputStream out=new BufferedOutputStream(o);
WritableByteChannel ch=Channels.newChannel(o);
//can i use
//WritableByteChannel ch=Channels.newChannel(out);

String msg="Hi how are you and what are you doing...";
out.write(msg.getBytes());
out.flush();

String fname = "hello.txt";
String fname2 = "input";
long fileSize = new File(fname).length();

FileChannel fc = new FileInputStream(fname).getChannel();
FileChannel fc2 = new FileInputStream(fname2).getChannel();

fc.transferTo(0, fc.size(), ch);
fc2.transferTo(0, fc2.size(), ch);

fc.close();
fc2.close();
out.close();
ch.close();
4

1 回答 1

0

它将作为 zeroCopy 吗?

不,您必须从 a 开始SocketChannel,而不是 aSocket,并直接在transferTo().

我有一些限制,比如必须发送第一个标题部分(文件和用户相关信息)

那么你不能用零拷贝来做到这一点。

然后文件内容。

你可以达到的那部分。

请注意,transferTo()未指定在单个呼叫中进行整个传输。您必须循环,注意返回值并相应地调整偏移量,直到全部完成。

于 2014-06-26T06:02:09.030 回答