Java File Read via ByteBuffer ClientReadWithWait(SocketChannel sc)

Here you can find the source of ClientReadWithWait(SocketChannel sc)

Description

Client Read With Wait

License

Open Source License

Declaration

public static String ClientReadWithWait(SocketChannel sc) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Main {
    public static String ClientReadWithWait(SocketChannel sc) {
        StringBuilder sb = new StringBuilder();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.clear();/*from  w  w w .  j  a v a  2  s .  com*/
        long timeout = 5000;
        long now = System.currentTimeMillis();
        while (!sb.toString().trim().endsWith("#!")) {
            try {
                sc.read(buffer);
                sb.append(new String(buffer.array()));
                buffer.clear();
            } catch (IOException e) {
                return null;
            }
            if (System.currentTimeMillis() - now > timeout) {
                System.out.println(sb.toString());
                System.out.println("client read timeout,cancel!");
                return null;
            }
        }
        return sb.toString().trim();

    }
}

Related

  1. blockingRead(SocketChannel so, long timeout, int bytes)
  2. channelCopy(@Nonnull @WillNotClose final ReadableByteChannel aSrc, @Nonnull @WillNotClose final WritableByteChannel aDest)
  3. channelCopy2(ReadableByteChannel src, WritableByteChannel dest)
  4. ClientReadWithBlock(SocketChannel sc)
  5. copy(final ReadableByteChannel src, final WritableByteChannel dest)
  6. copy(final ReadableByteChannel srcChannel, final WritableByteChannel destChannel)
  7. copyChannel(int bufferSize, ReadableByteChannel source, WritableByteChannel destination)
  8. copyStream(BufferedReader reader, BufferedWriter writer)