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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;public classEchoServer {public staticSelectorLoop connectionBell;public staticSelectorLoop readBell;public boolean isReadBellRunning=false;public static voidmain(String[] args) throws IOException {newEchoServer().startServer();
}public voidstartServer() throws IOException {
connectionBell= newSelectorLoop();
readBell= newSelectorLoop();
ServerSocketChannel ssc=ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(7878));
ssc.configureBlocking(false);
ssc.register(connectionBell.getSelector(), SelectionKey.OP_ACCEPT);newThread(connectionBell).start();
}public classSelectorLoop implements Runnable {privateSelector selector;private ByteBuffer temp = ByteBuffer.allocate(1024);publicSelectorLoop() throws IOException {this.selector =Selector.open();
}publicSelector getSelector() {return this.selector;
}public voidrun() {while(true) {try{this.selector.select();
Set selectKeys = this.selector.selectedKeys();
Iterator it =selectKeys.iterator();while(it.hasNext()) {
SelectionKey key=it.next();
it.remove();this.dispatch(key);
}
}catch(IOException e) {
e.printStackTrace();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}public voiddispatch(SelectionKey key) throws IOException, InterruptedException {if(key.isAcceptable()) {
ServerSocketChannel ssc=(ServerSocketChannel) key.channel();
SocketChannel sc=ssc.accept();
sc.configureBlocking(false);
sc.register(readBell.getSelector(), SelectionKey.OP_READ);
synchronized(EchoServer.this) {if (!EchoServer.this.isReadBellRunning) {
EchoServer.this.isReadBellRunning = true;newThread(readBell).start();
}
}
}else if(key.isReadable()) {
SocketChannel sc=(SocketChannel) key.channel();int count =sc.read(temp);if (count < 0) {
key.cancel();
sc.close();return;
}
temp.flip();
String msg= Charset.forName("UTF-8").decode(temp).toString();
System.out.println("Server received ["+msg+"] from client address:" +sc.socket());//Thread.sleep(1000);
sc.write(ByteBuffer.wrap(msg.getBytes(Charset.forName("UTF-8"))));
temp.clear();
}
}
}
}