构建网络服务端主程序:TigerServer.java
package hxb.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TigerServer implements Runnable {
// 服务器端口
private int port;
// 异步通道组,共享资源池
private AsynchronousChannelGroup asyncChannelGroup;
// 异步服务套接字通道
private AsynchronousServerSocketChannel serverSocketChannel;
/**
* 构造函数,完成服务端初始化
*
* @param port
* 监听端口
* @throws IOException
*/
public TigerServer(int port) throws IOException {
this.port = port;
ExecutorService executor = Executors.newFixedThreadPool(30);
asyncChannelGroup = AsynchronousChannelGroup.withThreadPool(executor);
serverSocketChannel = AsynchronousServerSocketChannel.open(asyncChannelGroup).bind(new InetSocketAddress(port));
}
@Override
public void run() {
AcceptHandler acceptHandler = new AcceptHandler();
serverSocketChannel.accept(serverSocketChannel, acceptHandler);
while(true)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
new Thread(new TigerServer(9527)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}