服务端代码
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
public class MultiplexerTimeServer implements Runnable {
private Selector selector;
private ServerSocketChannel servChannel;
private volatile boolean stop = false;
public MultiplexerTimeServer( int port) {
try {
selector = Selector.open();
servChannel = ServerSocketChannel.open();
servChannel.configureBlocking(false);
servChannel.socket().bind(new InetSocketAddress(port),1024);
servChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("time server is start on port "+port);
}catch (IOException e){
e.printStackTrace();
System.exit(1);
}
}
public void stop(){
this.stop = true;
}
@Override
public void run() {
while (!stop){
try{
selector.select(1000);
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
SelectionKey key ;
while (iterator.hasNext()){
key = iterator.next();
iterator.remove();
try{
handlerKey(key);
}catch (Exception e){
key.cancel();
if (key.channel() != null)
key.channel().close();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
if (selector != null) {
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handlerKey(SelectionKey key) throws IOException {
if (key.isValid()){
if (key.isAcceptable()){
ServerSocketChannel channel = (ServerSocketChannel)key.channel();
SocketChannel accept = channel.accept();
accept.configureBlocking(false);
accept.register(selector,SelectionKey.OP_READ);
}
if (key.isReadable()){
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
SocketChannel socketChannel = (SocketChannel)key.channel();
int readBytes = socketChannel.read(readBuffer);
if (readBytes > 0){
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String msg = new String(bytes, "UTF-8");
System.out.println("receive msg:"+msg);
doWrite(socketChannel,System.currentTimeMillis()+"");
}else if (readBytes < 0){
key.cancel();
socketChannel.close();
}else {
}
}
}
}
private void doWrite(SocketChannel socketChannel, String response) throws IOException {
byte[] bytes = response.getBytes();
ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
byteBuffer.put(bytes);
byteBuffer.flip();
socketChannel.write(byteBuffer);
}
public static void main(String[] args) throws IOException {
MultiplexerTimeServer server = new MultiplexerTimeServer(8088);
new Thread(server,"timerServer-001").start();
}
}
客户端代码
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.Iterator;
import java.util.Set;
public class TimeClinetHandler implements Runnable {
private String host;
private int port ;
private Selector selector;
private SocketChannel socketChannel;
private volatile boolean stop = false;
public TimeClinetHandler(String host, int port) {
this.host = host;
this.port = port;
try{
selector = Selector.open();
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
}catch (Exception e){
e.printStackTrace();
System.exit(1);
}
}
@Override
public void run() {
try{
doConnection();
}catch (Exception e){
e.printStackTrace();
System.exit(-1);
}
System.out.println("after connect");
while (!stop){
try{
selector.select(1000);
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
SelectionKey key;
while (iterator.hasNext()){
key = iterator.next();
iterator.remove();
try{
handInput(key);
}catch (Exception e){
key.cancel();
if (key.channel() != null)
key.channel().close();
}
}
}catch (Exception e){
e.printStackTrace();
System.exit(-1);
}
}
if (selector != null) {
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handInput(SelectionKey key) throws IOException {
if (key.isValid()){
SocketChannel channel = (SocketChannel)key.channel();
if (key.isConnectable()){
if (channel.finishConnect()){
channel.register(selector,SelectionKey.OP_READ);
doWrite(socketChannel);
}else {
System.exit(-1);
}
}
if (key.isReadable()){
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int readbytes = channel.read(readBuffer);
if (readbytes > 0){
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String msg = new String(bytes, "UTF-8");
System.out.println(" client get msg:"+msg);
this.stop = true ;
}else if (readbytes < 0){
key.cancel();
channel.close();
}
}
}
}
private void stop() {
this.stop = true;
}
private void doConnection() throws IOException {
if (socketChannel.connect(new InetSocketAddress(host,port))) {
socketChannel.register(selector,SelectionKey.OP_READ);
doWrite(socketChannel);
}else {
socketChannel.register(selector,SelectionKey.OP_CONNECT);
}
}
private void doWrite(SocketChannel socketChannel) throws IOException {
byte[] bytes = "query for time".getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
writeBuffer.put(bytes);
writeBuffer.flip();
socketChannel.write(writeBuffer);
if (!writeBuffer.hasRemaining()){
System.out.println("client send msg succ");
}
}
public static void main(String[] args) throws IOException {
new Thread(new TimeClinetHandler("127.0.0.1",8088)).start();
}
}