Aio Socket通信报错,且无法正确获取数据

孙海峰VIP 2017-05-13 09:37:04
代码如下:
public class AioServer {
private AsynchronousServerSocketChannel server;
private ByteBuffer send = ByteBuffer.allocate(2048);
private ByteBuffer recive = ByteBuffer.allocate(2048);

public AioServer(int port) throws IOException {
server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
}

public void startup() throws Exception {
System.out.println("========服务已启动=========");
AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(4));

// 监听客户端连接
server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

@Override
public void completed(AsynchronousSocketChannel result, Void attachment) {
recive.clear();
result.read(recive); //接收客户端数据
System.out.println("?????"+new String(recive.array()));
send.clear();
send.put(doSomething().getBytes());
send.flip();
result.write(send); //反馈结果
}

private String doSomething() {
//此处应有业务逻辑
return "处理成功";
}

@Override
public void failed(Throwable exc, Void attachment) {

}

});

group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}

public static void main(String[] args) {
try {
new AioServer(9000).startup();
} catch (Exception e) {
e.printStackTrace();
}
}
}

public class AioClient {

private int port;
private ByteBuffer send = ByteBuffer.allocate(2048);
private ByteBuffer recive = ByteBuffer.allocate(2048);

public AioClient(int port) {
this.port = port;
}

public Object send(String message) throws IOException {
AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
for (;;) {
client.connect(new InetSocketAddress(port), null, new CompletionHandler<Void, AsynchronousSocketChannel>() {

@Override
public void completed(Void result, AsynchronousSocketChannel attachment) {
send.clear();
send.put(message.getBytes());
send.flip();
attachment.write(send);
recive.clear();
attachment.read(recive);
System.out.println("计算结果:" + new String(recive.array()));

}

@Override
public void failed(Throwable exc, AsynchronousSocketChannel attachment) {

}



});
}
}

public static void main(String[] args) {
try {
new AioClient(9000).send("hello aio");
} catch (IOException e) {
e.printStackTrace();
}
}
}

运行上述代码客户端将会抛出如下异常

Exception in thread "main" java.nio.channels.ConnectionPendingException
at sun.nio.ch.UnixAsynchronousSocketChannelImpl.implConnect(UnixAsynchronousSocketChannelImpl.java:314)
at sun.nio.ch.AsynchronousSocketChannelImpl.connect(AsynchronousSocketChannelImpl.java:209)
at com.threadtest.aio.AioClient.send(AioClient.java:30)
at com.threadtest.aio.AioClient.main(AioClient.java:57)
Exception in thread "Thread-9"


初次接触Aio对此不是很熟,求指点迷津。
...全文
205 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
孙海峰VIP 2017-05-15
  • 打赏
  • 举报
回复
不能沉。。。。

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧