我正在使用 Java NIO 做客户端服务器 Java 程序。基本上对于服务器代码,我从这里获取。而对于客户端,我从这里拿走了。现在看来还不错。我现在想要实现的是将数据从客户端发送到服务器,服务器将发送回客户端。
但我的逻辑有问题。假设我放了“AMessage”,然后我必须放“BMessage”才能从服务器检索“AMessage”。我做了调试,似乎我key.isConnectable()
的总是 return true
。我尝试设置关键兴趣,重新注册它,但我还没有找到任何解决方案。
我试过这个key.interestOps(0);
,,myChannel.register(selector, SelectionKey.OP_READ);
但似乎什么也没发生。isConnectable
仍然返回 true。我发现其他人告知的一些问题说这是本地主机问题。我不知道。但现在我在 localhost 上运行服务器和客户端。有人有什么想法吗?
谢谢 :)
编辑:这是我的代码的一部分:-
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();
}
}