Created
October 24, 2016 08:03
-
-
Save s4553711/9059a15f673f3f4802653b8653514ce5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment