我正在使用Java NIO做客户端服务器Java程序。基本上是服务器代码,我从这里拿的。至于客户端,我从这里接手。现在看来还不错。我现在想要实现的是将数据从客户端发送到服务器,服务器将发送回客户端。
但是我在逻辑上有问题。假设我输入"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
或其他。如果
finishConnect()
抛出异常,说明连接失败,必须关闭通道。你调用
finishConnect()
两次:一次在try
块,一次在记录状态。去掉第二个调用,使用第一个调用的结果(如果有的话)。我会重新组织这个日志(a)finishConnect()
的成功,(b)finishConnect()
的失败,和(c)finishConnect()
的例外,都是分开的。你最终的
System.out.println()
只是三个案例中的两个谎言。不要告诉自己那些你不知道是真的事情。这只会混淆图像。你假设连接是可读的,而不是测试
isReadable().