AIOClient.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package cn.hhj.aio;
  2. import java.net.InetSocketAddress;
  3. import java.nio.ByteBuffer;
  4. import java.nio.channels.AsynchronousSocketChannel;
  5. import java.nio.channels.CompletionHandler;
  6. /**
  7. * AIO客户端
  8. */
  9. public class AIOClient {
  10. private final AsynchronousSocketChannel client;
  11. public AIOClient() throws Exception{
  12. client = AsynchronousSocketChannel.open();
  13. }
  14. public void connect(String host,int port)throws Exception{
  15. client.connect(new InetSocketAddress(host,port),null,new CompletionHandler<Void,Void>() {
  16. @Override
  17. public void completed(Void result, Void attachment) {
  18. try {
  19. client.write(ByteBuffer.wrap("这是一条测试数据".getBytes())).get();
  20. System.out.println("已发送至服务器");
  21. } catch (Exception ex) {
  22. ex.printStackTrace();
  23. }
  24. }
  25. @Override
  26. public void failed(Throwable exc, Void attachment) {
  27. exc.printStackTrace();
  28. }
  29. });
  30. final ByteBuffer bb = ByteBuffer.allocate(1024);
  31. client.read(bb, null, new CompletionHandler<Integer,Object>(){
  32. @Override
  33. public void completed(Integer result, Object attachment) {
  34. System.out.println("IO操作完成" + result);
  35. System.out.println("获取反馈结果" + new String(bb.array()));
  36. }
  37. @Override
  38. public void failed(Throwable exc, Object attachment) {
  39. exc.printStackTrace();
  40. }
  41. }
  42. );
  43. try {
  44. Thread.sleep(Integer.MAX_VALUE);
  45. } catch (InterruptedException ex) {
  46. System.out.println(ex);
  47. }
  48. }
  49. public static void main(String args[])throws Exception{
  50. new AIOClient().connect("localhost",8000);
  51. }
  52. }