Exception in thread "main" java.nio.channels.NotYetConnectedException

 import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.net.InetSocketAddress;
import java.util.concurrent.Future;
import java.nio.ByteBuffer; public class SimpleAIOServer{
static final int PORT = 30000;
public static void main(String[] args) throws Exception{
try(
//创建AsynchronousServerSocketChannel对象
AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open()
){
//指定在指定地址、端口监听
serverChannel.bind(new InetSocketAddress(PORT));
while(true){
//采用循环接受来自客户端的连接
Future<AsynchronousSocketChannel> future = serverChannel.accept();
//获取连接完成后返回的AsynchronousSocketChannel
AsynchronousSocketChannel socketChannel = future.get();
//执行输出
socketChannel.write(ByteBuffer.wrap("欢迎你来到AIO的世界!".getBytes("UTF-8"))).get();
}
}
}
}
 import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.net.InetSocketAddress;
import java.util.concurrent.Future;
import java.nio.ByteBuffer; public class SimpleAIOClient{
static final int PORT = 30000;
public static void main(String[] args) throws Exception{
//用于读取数据的ByteBuffer
ByteBuffer buff = ByteBuffer.allocate(1024);
Charset utf = Charset.forName("utf-8");
try(
//创建AsynchronousSocketChannel对象
AsynchronousSocketChannel clientChannel = AsynchronousSocketChannel.open()
){
//连接远程服务器
clientChannel.connect(new InetSocketAddress("127.0.0.1", PORT));
buff.clear();
//从clientChannel中读取数据
clientChannel.read(buff).get();
buff.flip();
//将buff中的内容转换为字符串
String content = utf.decode(buff).toString();
System.out.println("服务器信息:" + content);
}
}
}

Exception in thread "main" java.nio.channels.NotYetConnectedException

运行上述代码会出现Exception in thread "main" java.nio.channels.NotYetConnectedException并提示在at SimpleAIOClient.main(SimpleAIOClient.java:21)报错。

NotYetConnectedException是尚未连接的错误,代码出错原因:

客户端和服务端没有建立连接就执行了Socket通信,代码上的错误位置是:

SimpleAIOClient.java中第18行:

//连接远程服务器
clientChannel.connect(new InetSocketAddress("127.0.0.1", PORT));

因为这一行没有检查异步IO操作是否完成,只有异步IO操作完成客户端和服务端的连接才能建立。

而异步IO操作是否完成的标志是clientChannel有一个Future返回值,得到它才能确保异步IO操作执行完成:

//连接远程服务器
clientChannel.connect(new InetSocketAddress("127.0.0.1", PORT)).get();//得到Future返回值,否则连接不会建立。

上一篇:Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 0 解决方法: 要对切割字符进行转义\\


下一篇:Chrome Extension 扩展程序 小白入门