62,634
社区成员




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"