s4553711
10/24/2016 - 8:03 AM

NIO-client-byteBuffer-mode1.java

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioRunner {
	public static void main(String[] args) {
		SocketChannel client[] = new SocketChannel[args.length];
		try {
			for (int j = 0; j < args.length; j++) {
				String[] argPart = args[j].split(":");
				if (argPart.length < 2) {
					System.out.println("Illegal argument.");
					return;
				}
				client[j] = SocketChannel.open();
				client[j].connect(new InetSocketAddress(argPart[0], Integer.valueOf(argPart[1])));
				client[j].configureBlocking(false);
			}
			BufferedInputStream bufferedInputStream = new BufferedInputStream(
					System.in);
			int c = 0;
			byte[] data = new byte[1024 * 32];
			ByteBuffer buffer = ByteBuffer.allocate(1024 * 32);
			while (bufferedInputStream.read(data) != -1) {
//				buffer = ByteBuffer.wrap(data);
				buffer.put(data);
				buffer.flip();
				
				client[c % client.length].write(buffer);
//				while(buffer.hasRemaining()) {
//				    client[c % client.length].write(buffer);
//				}

				if (buffer.hasRemaining()) {
					buffer.compact();
				} else {
					buffer.clear();
				}
//				buffer.clear();
				c++;
			}
			bufferedInputStream.close();

			for (SocketChannel ch : client) {
				ch.close();
			}
		} catch (IOException e) {
			System.out.println("IOException");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}