我正在使用 Java NIO 做客户端服务器 Java 程序。基本上对于服务器代码,我取自 here 。对于客户端,我取自 here 。现在看来不错。我现在想要实现的是将数据从客户端发送到服务器,服务器将数据发送回客户端。
但是我的逻辑有问题。假设我放置了“AMessage”,那么我必须放置“BMessage”才能从服务器检索“AMessage”。我进行了调试,似乎我的 key.isConnectable()
始终返回 true
。我尝试设置关键兴趣,重新注册它,但我还没有找到任何解决方案。
我已经尝试过这个 key.interestOps(0);
, myChannel.register(selector, SelectionKey.OP_READ);
,但似乎什么也没发生。 isConnectable
仍然返回 true。我发现其他人告知的一些问题说这是本地主机问题。我不知道。但现在我在本地主机上运行服务器和客户端。有人有什么想法吗?
谢谢:)
编辑:这是我的代码的一部分:-
if (key.isConnectable()) {
if (myChannel.isConnectionPending()) {
try{
myChannel.finishConnect();
}
catch(IOException e){
System.out.println(e);
}
System.out.println("Status of finishCOnnect(): " + myChannel.finishConnect() );
System.out.println("Connection was pending but now is finished connecting.");
}
ByteBuffer bb = null;
ByteBuffer incomingBuffer = null;
Scanner input = new Scanner(System.in); // Declare and Initialize the Scanner
while (true) {
System.out.println("Status isReadable is " + key.isReadable() + " and isWritable is " + key.isWritable() +
" and isConnectable is " + key.isConnectable());
readMessage(key); //read if server send data
//send data to server here
String inputFromClient = input.nextLine(); //Get the input from client
System.out.println("debugging after get input...");
bb = ByteBuffer.allocate(inputFromClient.length()); //Allocate buffer size according to input size
byte[] data = inputFromClient.getBytes("UTF-8"); //convert the input to form of byte
bb = ByteBuffer.wrap(data); //wrap string inside a buffer
myChannel.write(bb); //Write the buffer on the channel to send to the server
bb.clear();
}
}
最佳答案
if (key.isConnectable()) {
if (myChannel.isConnectionPending()) {
try{
myChannel.finishConnect();
}
catch(IOException e){
System.out.println(e);
}
System.out.println("Status of finishCOnnect(): " + myChannel.finishConnect() );
System.out.println("Connection was pending but now is finished connecting.");
}
这里有几个问题。
isConnectionPending()
测试是多余的。它必须处于待处理状态,否则您将不会获得该事件,但您可能会通过测试它来诱惑普罗维登斯。摆脱这个测试。您没有通过
finishConnect()
调用执行正确的操作。如果finishConnect()
返回true那么就可以取消注册OP_CONNECT
并注册OP_READ
或其他。如果返回 false,则不行。如果
finishConnect()
抛出异常,则连接失败,您必须关闭 channel 。您调用
finishConnect()
两次:一次在try
block 中,一次在记录状态时。摆脱第二个调用并使用第一个调用的结果(如果有)。我将重新组织它以记录(a)来自finishConnect()
的成功,(b) 来自finishConnect()
的失败,以及 (c) 来自finishConnect() 的异常
,全部分开。您的最终
System.out.println()
在这三种情况中的两种情况下只是一个谎言。不要告诉自己一些你不知道是真的事情。它只是混淆了图片。如上所述分别记录每个案例。您假设连接可读,而不是测试
isReadable()。
关于Java NIO isConnectable 始终返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15676904/