gpt4 book ai didi

java - 如何使这个非阻塞服务器成为多线程的?

转载 作者:搜寻专家 更新时间:2023-11-01 01:57:37 24 4
gpt4 key购买 nike

我正在尝试允许多个连接到一个小型 Java 服务器类型的应用程序。它按原样工作正常,但如果一个连接打开然后挂起,则所有后续连接都将挂起。我不确定如何处理每个连接,最多大约 20 个并发连接在它们自己的线程中,同时跟踪哪个线程属于哪个客户端等。我目前的代码是:

private void init() {
try {
// Create the server socket channel
ServerSocketChannel server = ServerSocketChannel.open();
// nonblocking I/O
server.configureBlocking(false);
// host-port
server.socket().bind(new InetSocketAddress(host, port));
System.out.println("Server connected on " + host + ":" + port);
// Create the selector
Selector selector = Selector.open();
// Recording server to selector (type OP_ACCEPT)
server.register(selector, SelectionKey.OP_ACCEPT);
// Infinite server loop
for (;;) {
// Waiting for events
selector.select();
// Get keys
Set keys = selector.selectedKeys();
Iterator i = keys.iterator();
// For each keys...
while (i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
// Remove the current key
i.remove();
// if isAccetable = true
// then a client required a connection
if (key.isAcceptable()) {
// get client socket channel
SocketChannel client = server.accept();
// Non Blocking I/O
client.configureBlocking(false);
// recording to the selector (reading)
client.register(selector, SelectionKey.OP_READ);
continue;
}
// then the server is ready to read
if (key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
// Read byte coming from the client
int BUFFER_SIZE = 32;
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
try {
client.read(buffer);
} catch (Exception e) {
// client is no longer active
e.printStackTrace();
continue;
}
buffer.flip();
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buffer);
Handler dataHandler = new Handler();
client.write(ByteBuffer.wrap(dataHandler.processInput(charBuffer.toString()).getBytes()));
client.socket().close();
continue;
}
}
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}

最佳答案

每当我需要编写套接字服务器时,我都会避免使用低级 JVM 类,因为需要处理所有细节。

相反,我使用 Apache Mina .这是一个用于编写高性能非阻塞多线程套接字服务器的 Java 库。

使用 Mina 的另一个好处是它强制执行 clean architecture (IoFilters、协议(protocol)解码器)使您的代码更加模块化并更易于维护。

关于java - 如何使这个非阻塞服务器成为多线程的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4802523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com