Skip to content

Instantly share code, notes, and snippets.

@honwhy
Created December 17, 2019 15:54
Show Gist options
  • Save honwhy/76d188beb4712dfe0757f28535caa787 to your computer and use it in GitHub Desktop.
Save honwhy/76d188beb4712dfe0757f28535caa787 to your computer and use it in GitHub Desktop.
selector in client side(sorry forget the link from stackoverflow)
package com.honey;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.IntStream;
public class TcpTimeClient {
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.out.println("usage: <address> <port1> <port2>...");
System.exit(1);
}
try (final Selector selector = Selector.open()) {
tryAllConnections(selector, args[0],
Arrays.stream(args).skip(1).mapToInt(Integer::parseInt));
if (selector.keys().size() == 0) {
System.out.println("no connection can be attempted");
System.exit(1);
}
boolean gotResp = false;
while (!gotResp) {
if (selector.select(3000) == 0) {
System.out.print("-");
continue;
}
final Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
final SelectionKey key = iter.next();
if (key.isConnectable()) {
final SocketChannel sc = (SocketChannel) key.channel();
if (sc.finishConnect()) {
System.out.println("connected to: " + sc.getRemoteAddress());
key.interestOps(SelectionKey.OP_READ);
}
}
if (key.isReadable() && !gotResp) {
final SocketChannel sc = (SocketChannel) key.channel();
System.out.println("winner from: " + sc.getRemoteAddress());
final ByteBuffer bb = ByteBuffer.allocate(512);
final int bytesRead = sc.read(bb);
if (bytesRead == -1) {
System.out.println(" closed prematurely");
gotResp = true;
break;
}
System.out.println(" replied: " + new String(bb.array(), 0, bytesRead));
gotResp = true;
// just care about staff from first read
sc.close();
}
iter.remove();
}
}
closeAll(selector);
}
}
private static void closeAll(Selector selector) throws IOException {
for (SelectionKey key : selector.keys()) {
key.channel().close();
}
}
private static void tryAllConnections(Selector selector, String address, IntStream ports) {
ports.forEach(port -> {
try {
final SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress(address, port));
sc.register(selector, SelectionKey.OP_CONNECT);
} catch (IOException e) {
System.out.println("connecting attempt to " + address + ":" + port + " failed");
}
});
}
public static Process start(String ...args) throws IOException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = TcpTimeClient.class.getCanonicalName();
String[] cmd = {javaBin, "-cp", classpath, className};
List<String> command = new ArrayList<>(Arrays.asList(cmd));
command.addAll(Arrays.asList(args));
ProcessBuilder builder = new ProcessBuilder(command.toArray(new String[0]));
return builder.start();
}
}
package com.honey;
import org.junit.Test;
import java.io.*;
public class TestTcpTimeClient {
@Test
public void test() throws IOException, InterruptedException {
String address = "bing.com";
Process process = TcpTimeClient.start(address, "80", "82", "83");
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
process.destroy();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment