多线程池服务器监听Java中的多个端口



我想弄清楚如何创建一个Java多线程服务器,可以监听多个端口,并为每个端口提供线程池,它接受来自的请求。

我已经实现了一个功能良好的多线程池服务器监听单个报告,如下所示:

public void run() {
synchronized (this) {
this.runningThread = Thread.currentThread();
}
openSocketServer();
while (!isStopped()) {
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if (isStopped()) {
System.out.println("Server Stopped.");
break;
}
throw new RuntimeException("Error with accepting client connection", e);
}
this.threadPool.submit(new HandlerRichieste(clientSocket, this));
}
this.threadPool.shutdown();
System.out.println("Server stopped");
}

我设法实现了一个服务器监听多个端口与NIO库;这个实现的问题是,它只使用一个线程来处理来自不同端口的请求,因此按顺序处理它们并降低性能:

Selector selector = Selector.open();
int[] ports = {4000,4001,6000};
for (int port : ports) {
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new InetSocketAddress(port));
// from here we are only interested when accept evens occur on this socket
server.register(selector, SelectionKey.OP_ACCEPT); 
}
while (selector.isOpen()) {
selector.select();
Set readyKeys = selector.selectedKeys();
Iterator iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
if (key.isAcceptable()) {
SocketChannel client = server.accept(); //SERVER CANNOT BE RESOLVED!!!!
Socket socket = client.socket();
// create new thread to deal with the connection coming from that port (closing both socket and client when done)
}
}
}

我如何合并它们-导致服务器监听多个端口,每个端口都有一个线程池?是否有可能在不使用NIO库的情况下创建一个侦听多个端口的多线程池服务器?如果是这样,谁能告诉我在没有Java NIO的情况下为每个端口提供线程池的机制?

您已经能够创建一个服务器,其中一个线程在一个端口上等待连接,并使用来自特定池的线程为传入连接提供服务。

是什么阻止你创建这个模式三次?然后监听三个端口,并使用来自三个特定线程池的线程为传入连接提供服务。你唯一需要注意的是:在一个套接字上等待连接可能会阻塞线程。

作为解决方案,只需创建三个线程,每个线程侦听一个端口。

最新更新