0

I have some doubt regarding using Channels.newChannel(OutputStream/InputStream) in zeroCopy operation. Will it serve as zeroCopy. I have some restriction like have to send 1st header part(file and user related information) then file content. For testing, i also override BufferedOutputStream, but on fileChannel.transferTo call, it is calling my override methods... Please help me how to achieve zeroCopy in such circumstances(header+content).

part of testing code:

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();
Upendra
  • 87
  • 1
  • 10

1 Answers1

0

Will it serve as zeroCopy.

No. You would have to start with a SocketChannel for that, not a Socket, and use it directly in transferTo().

I have some restriction like have to send 1st header part(file and user related information)

Well you can't do that with zero copy.

then file content.

That part you can achieve.

Note that transferTo() isn't specified to do the entire transfer in a single call. You have to loop, noting the return value and adjusting the offset accordingly until it's all done.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thanks EJP. My problem is : have to use single stream/channel for both header and content. I will try to solve with nio socketChannel. I m thinking, for header part will send using socketChannel->socket->outputstream then flush output stream after that same socketChannel will use as argument for FileChannel.transferTo. will get back, if got any problem. meanwhile, please suggest me if this is not a correct way to solve this problem... – Upendra Jun 26 '14 at 06:16
  • With socket we can set timeout for connection as well for read/write. Is this possible for SocketChannel? Then how? – Upendra Jun 26 '14 at 09:19
  • First, forget about the output streams. Use ByteBuffer to send your headers. Second, you can achieve a connect timeout via SocketChannel.socket().connect(). – user207421 Jun 26 '14 at 09:28