我有一个客户端应用程序可以连接到我的服务器应用程序,而且一切都很好,直到接收到来自客户端的消息为止。服务器应该从客户端接收消息,然后将其发送给所需的收件人。我让我的服务器通过,并使用选择器选择接收到的所有输入,如果它是来自客户端的消息,则会命中handleIncomingMessage方法。问题在于它注册了客户端,但从未命中过handleIncomingMessage方法。
我尝试在服务器(从OP_ACCEPT到OP_CONNECT)和客户端(从OP_ACCEPT到OP_READ和OP_WRITE)上都更改选择器的SelectionKey,但这似乎不起作用。
public void run(int port) {
this.port = port;
try {
selector = Selector.open();
bindAndListenToPort();
} catch (IOException e) {
System.out.println(Shared.getErrorMessage(20));
e.printStackTrace();
}
while (true) {
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
registerNewClient(key);
}
// Pending
else if (key.isReadable()) {
handleIncomingMessage(key);
}
iterator.remove();
}
} catch (IOException e) {
System.out.println(Shared.getErrorMessage(21));
}
}
}
private void registerNewClient(SelectionKey key) throws IOException {
SocketChannel client = serverSocket.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
client.register(selector, SelectionKey.OP_WRITE);
}
private void bindAndListenToPort() throws IOException {
serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress("localhost", port));
serverSocket.configureBlocking(false);
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
}
``
I expected the server to hit the handleIncomingMessage method, but it never does (I chose not to include the actual method in my example because what it does currently is not relevant.)