[Nbserver-devel] Re: question
Status: Beta
Brought to you by:
szegedia
From: Attila S. <sze...@fr...> - 2002-04-23 11:48:56
|
the pipe's "auto-transfer" feature is useful when you want to have th= e pipe attempt writing to its associated auto-write channel whenever you wri= te to the pipe. If you want to transfer a file that is readily available (i= .e. it resides on a hard drive instead of being dinamically generated conten= t) you'd be better off by writing a protocol handler that opens a channe= l to the file, and whenever your protocol handler's "tryToWrite" method is called, call fileChannel.transferTo(socketChannel, offset, length), adjusting the offset along the way. A minimalistic protocol handler that - after a client connects - send= s over a file would look like the code below. Note that you needn't use the nonblocking pipe - this is because nonblocking pipe is for situations= where your code generates the data. When the data is readily available in a= file, you can send it over more efficiently. public class FileSendProtocolHandler implements ProtocolHandler { private final FileChannel fileChannel; private final SocketChannel socketChannel private long offset =3D 0; private final long length; public FileSendProtocolHandler(File file, SocketChannel socketCha= nnel) throws IOException { length =3D file.length(); fileChannel =3D new FileInputStream(file).getChannel(); this.socketChannel =3D socketChannel; } public int validOps() { return SelectionKey.OP_WRITE; } public boolean tryToRead() throws IOException { return true; } public boolean tryToWrite() throws IOException { boolean endWrite =3D false; try { while(offset < length) { int written =3D fileChannel.transferTo(offset, 4096, socketChannel); if(written =3D=3D 0) break; offset +=3D written; } endWrite =3D offset =3D=3D length; } catch(IOException e) { endWrite =3D true; e.printStackTrace(); throw e; } finally { if(endWrite) { fileChannel.close(); } } return endWrite; } -- Attila Szegedi home: http://www.szegedi.org ----- Original Message ----- =46rom: ivanwang To: sze...@us... Sent: 2002. =E1prilis 22. 18:05 Subject: question hi,szegedia I have study the code of nbserver, but i have some questions about it= . I want to send a huge file and I have done as the following: 1) create a GlobalByteBufferPool object--pool 2)according to MEMORY_BLOCKSIZE,separate the huge file into blocks, a= nd call pool.putbuffer to be a ByteBuffer list. 3) create a NonblockingPipe object pipe=3D NonblockingPipe(pool) 4)call pipe.setAutoWriteChannel() and pipe.autoTransferTo() to send o= ut the huge file. Is it okay? would you please give me some ideas? Thank you very much! ivan |