AIO Client

public class AIOClient implements Runnable{

	private Logger logger=LoggerFactory.getLogger("AIO client:");
	private AsynchronousSocketChannel  client;//=AsynchronousSocketChannel.open();
	private String host="127.0.0.1";
	private int port=7001;
	private InetSocketAddress  serverAddress;
	
	public AIOClient() {
		serverAddress=new InetSocketAddress(host,port);		
	}
	public AIOClient(String host,int port) {
		this.host=host;
		this.port=port;
		serverAddress=new InetSocketAddress(host,port);		
	}
	
	public void connect_server() throws IOException {
		// 开启通道
		client = AsynchronousSocketChannel.open();
		client.setOption(StandardSocketOptions.TCP_NODELAY, true);  
		client.setOption(StandardSocketOptions.SO_SNDBUF, 1024);  
		client.setOption(StandardSocketOptions.SO_RCVBUF, 1024);  
        //建立连接
		client.connect(serverAddress,null,new ConnectHandler(client));
	}
	@Override
	public void run() {
		while(true) {
			
		}
	}	
	private class ConnectHandler implements CompletionHandler<Void,Void>{
		private AsynchronousSocketChannel client;
		public ConnectHandler(AsynchronousSocketChannel client) {
			this.client=client;
		}
		@Override
		public void completed(Void result, Void attachment) {
			logger.info("客户端成功连接到服务器...");		
			try {  
				logger.info("远程地址:" +client.getRemoteAddress()); 
				logger.info("远程地址:" +client.getLocalAddress()); 
	            if (client.isOpen()) {  
	            	logger.info("client.isOpen:" + client.getRemoteAddress());  
	                ByteBuffer buffer = ByteBuffer.allocate(1024);  
	                //buffer.clear();  
	                client.read(buffer, client, new ReadHandler(buffer));  
	            }  

	        } catch (Exception e) {  
	            e.printStackTrace();  
	        } finally {  
	        	  
	        } 
		}

		@Override
		public void failed(Throwable exc, Void attachment) {
			logger.info("连接失败.....");
			try {
				client = AsynchronousSocketChannel.open();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				client.setOption(StandardSocketOptions.TCP_NODELAY, true);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			try {
				client.setOption(StandardSocketOptions.SO_SNDBUF, 1024);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			try {
				client.setOption(StandardSocketOptions.SO_RCVBUF, 1024);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			client.connect(serverAddress,null,new ConnectHandler(client));
		}
	}
	/*
	 * 
	 */
	private class ReadHandler implements CompletionHandler<Integer,AsynchronousSocketChannel>{

		private ByteBuffer buffer;  
		  
        public ReadHandler(ByteBuffer buffer) {  
            this.buffer = buffer;  
        }  
  
		@Override
		public void completed(Integer result, AsynchronousSocketChannel attachment) {
			try {  
                if (result ==-1) {			//连接断开
                	logger.info("连接断开.......");
                	attachment.close();  
                	logger.info("连接失败.....");
        			try {
        				attachment = AsynchronousSocketChannel.open();
        			} catch (IOException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        			try {
        				attachment.setOption(StandardSocketOptions.TCP_NODELAY, true);
        			} catch (IOException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}  
        			try {
        				attachment.setOption(StandardSocketOptions.SO_SNDBUF, 1024);
        			} catch (IOException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}  
        			try {
        				attachment.setOption(StandardSocketOptions.SO_RCVBUF, 1024);
        			} catch (IOException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        			attachment.connect(serverAddress,null,new ConnectHandler(attachment));
                } else if (result == 0) {  
                    logger.info("空数据"); // 处理空数据  
                } else {  
                    // 读取请求,处理客户端发送的数据  
                	buffer.flip();
        			byte[] read=new byte[result];
        			//("缓冲区: "+readCounter+"  "+read.length);
        			buffer.get(read,0,read.length);
        		    String expression=new String(read,"utf-8");
        			logger.info(expression);
                    //响应操作,服务器响应结果  
                    buffer.flip();  
                    attachment.write(buffer, attachment, new WriteHandler(buffer)); 
                    buffer.clear();
                    attachment.read(buffer, attachment, new ReadHandler(buffer));  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
			
		}

		@Override
		public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
			exc.printStackTrace();
			try {
				attachment.close();
			} catch (IOException e) {
				e.printStackTrace();
			}			
		}
	}
	private class WriteHandler implements CompletionHandler<Integer,AsynchronousSocketChannel>{
		
		private ByteBuffer buffer;
		
		public WriteHandler(ByteBuffer buffer) {
			this.buffer=buffer;
		}
		@Override
		public void completed(Integer result, AsynchronousSocketChannel attachment) {
			buffer.clear();
			logger.info("发送: "+result);
		}
		@Override
		public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
//			exc.printStackTrace();  
//            try {
//				server.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}  
		}
	}
	public static void main(String[] args) throws IOException, InterruptedException {
		
		AIOClient client=new AIOClient();
		client.connect_server();
		while(true) {
			Thread.sleep(1000);
		}
	}
}

1、关键参数 channel buffer handler

     a、AsyncchronousSocketChannel:

          异步客户端套接字通道

     b、 ConnectHandler implements  CompletionHandler<Void, Void> :

          连接事件注册类

     c、ReadHandler implements CompletionHandler<Integer,AsynchronousSocketChannel>:

          套接字读事件注册类

     d、WriteHandler implements CompletionHandler<Integer,AsynchronousSocketChannel>:

          套接字写事件注册类

2、工作流程

     打开通道->设置套接字参数->通道连接并注册处理事件类

    ----->在侦听事件类中完成方法设置参数并注册读处理事件类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值