public class TimeClientHandler implements Runnable {
private String host;
private int port;
private Selector selector;
private SocketChannel socketChannel;
private volatile boolean stop;
public TimeClientHandler(String host, int port) {
this.host = host;
this.port = port;
try {
selector = Selector.open();
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
if (socketChannel.connect(new InetSocketAddress(host, port))) {
socketChannel.register(selector, SelectionKey.OP_READ);
doSendReqMsg(socketChannel, "Hi Server !");
} else
socketChannel.register(selector, SelectionKey.OP_CONNECT);
} catch (IOException e) {
e.printStackTrace();
}
while (!this.stop) {
try {
selector.select(1000);
Set<SelectionKey> selectedKeys = selector.selectedKeys();
for (SelectionKey k : selectedKeys) {
selectedKeys.remove(k);
try {
doProcessResponse(k);
} catch (Exception e) {
if (k != null) {
k.cancel();
if (k.channel() != null)
k.channel().close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (selector != null) {
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void doProcessResponse(SelectionKey key) throws IOException {
if (!key.isValid())
return;
SocketChannel sc = (SocketChannel) key.channel();
if (key.isConnectable()) {
if (sc.finishConnect()) {
sc.register(selector, SelectionKey.OP_READ);
doSendReqMsg(sc, "Hi Server !");
} else {
throw new RuntimeException("连接失败");
}
}
if (key.isReadable()) {
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int readBytes = sc.read(readBuffer);
if (readBytes > 0) {
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String respMsg = new String(bytes, "UTF-8");
System.out.println("time : " + respMsg);
this.stop = true;
} else if (readBytes < 0) {
key.cancel();
sc.close();
} else {
}
}
}
private void doSendReqMsg(SocketChannel sc, String reqMsg) throws IOException {
byte[] req = reqMsg.getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
writeBuffer.put(req);
writeBuffer.flip();
sc.write(writeBuffer);
}
}