文件传输(异步和未来)

时间:2018-04-30 10:53:37

标签: java file asynchronous transfer

我有文件传输问题。我尝试读取文件并在SocketChannel

中传输此文件

服务器

private final AsynchronousFileChannel fileChannel;
private Future<Integer> writeOperation, readOperation;
private long positionWrite, positionRead;


if (key.isWritable()) {
      Storage storage = (Storage) key.attachment();
      SocketChannel socketChannel = (SocketChannel) key.channel();
      ByteBuffer buffer = ByteBuffer.allocate(1024);

      if (storage.fileChannel.size() >= storage.counter) {
           storage.counter+=1024;
           storage.fileReadAndWrite(buffer, socketChannel);
      } else {
           storage.close();
           socketChannel.close();
      }
}



void fileReadAndWrite(ByteBuffer buffer, SocketChannel socketChannel)
            throws InterruptedException, ExecutionException, IOException {
   try {
        if (readOperation != null)
           positionRead += readOperation.get(5, TimeUnit.SECONDS);

        readOperation = fileChannel.read(buffer, positionRead);
        buffer.flip();
        socketChannel.write(buffer);

   } catch (TimeoutException exc) {
        close();
        System.out.println("Read timeout");
   }
}

客户端

private static final int PORT = 1234;
private static final String HOST = "localhost";
private static final String FILE_NAME = "3.jpg";


private static InetSocketAddress serverAddress = new InetSocketAddress(HOST, PORT);

public static void main(String[] args) {
    try (SocketChannel socketChannel = SocketChannel.open(serverAddress)) {
        try (FileChannel fileChannel = FileChannel.open(
                Paths.get(FILE_NAME), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
            fileChannel.transferFrom(socketChannel, 0, Long.MAX_VALUE);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

当我运行此代码时,我得到下一个异常java.nio.BufferOverflowException或文件未完全转移。 你能告诉我怎样才能解决这个问题? All code

0 个答案:

没有答案