日期:2014-05-20 浏览次数:20961 次
public class SeekServer extends Thread{
private final int ACCPET_PORT = 55555;
private final int TIME_OUT = 3000;
private Selector mSelector = null;
private ServerSocketChannel mSocketChannel = null;
private ServerSocket mServerSocket = null;
private InetSocketAddress mAddress = null;
public SeekServer() {
long sign = System.currentTimeMillis();
try {
mSocketChannel = ServerSocketChannel.open();
if(mSocketChannel == null) {
System.out.println("can't open server socket channel");
}
mServerSocket = mSocketChannel.socket();
mAddress = new InetSocketAddress(ACCPET_PORT);
mServerSocket.bind(mAddress);
Log.i("server bind port is " + ACCPET_PORT);
mSelector = Selector.open();
mSocketChannel.configureBlocking(false);
SelectionKey key = mSocketChannel.register(mSelector, SelectionKey.OP_ACCEPT);
key.attach(new Acceptor());
Log.i("Seek server startup in " + (System.currentTimeMillis() - sign) + "ms!");
} catch (ClosedChannelException e) {
Log.e(e.getMessage());
} catch (IOException e) {
Log.e(e.getMessage());
}
}
public void run() {
Log.i("server is listening...");
while(!Thread.interrupted()) {
try {
if(mSelector.select(TIME_OUT) > 0) {
Log.i("find a new selection key");
Set<SelectionKey> keys = mSelector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
SelectionKey key = null;
while(iterator.hasNext()) {
key = iterator.next();
Runnable at = (Runnable) key.attachment();
if(at != null) {
at.run();
}
keys.clear();
}
}
} catch (IOException e) {
Log.e(e.getMessage());
}
}
}
class Acceptor implements Runnable{
public void run(){
try {
SocketChannel sc = mSocketChannel.accept();
new Handler(mSelector, sc);//开始处理这个Channel
} catch (ClosedChannelException e) {
Log.e(e);
} catch (IOException e) {
Log.e(e);
}
}
}
}