java NIO通信demo

server端

 

public class NIOServer {

	private Selector selector;
	public static void main(String[] args){
		NIOServer s = new NIOServer();
		s.initSelector();
		s.run();
	}
	
	public void run(){
		while(true){

			try{
				selector.select();
				Iterator it = selector.selectedKeys().iterator();
				while(it.hasNext()){
					SelectionKey key = (SelectionKey)it.next();
					it.remove();
					if(!key.isValid()){
						continue;
					}
					else if(key.isAcceptable()){
						accept(key);
					}
					else if(key.isReadable()){
						read(key);
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void read(SelectionKey key){
		SocketChannel sssc =(SocketChannel)key.channel();
		if(sssc.isOpen()&&sssc.isConnected()){
		System.out.println("read");
		new ReadThread(key).start();
		}
	}
	public void accept(SelectionKey key) throws Exception{
		System.out.println("有客户接入");
		ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
		SocketChannel sc = ssc.accept();
		sc.configureBlocking(false);
		sc.register(selector, SelectionKey.OP_READ);
	}
	public void initSelector(){
		try {
			selector = SelectorProvider.provider().openSelector();
			ServerSocketChannel channel = ServerSocketChannel.open();
			channel.configureBlocking(false);
			channel.socket().bind(new InetSocketAddress(8000));
			channel.socket().setReuseAddress(true);
			channel.register(selector, SelectionKey.OP_ACCEPT);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 

 

监听线程:取得客户端连接

 

public class ReadThread extends Thread{

	private SocketChannel sc;
	private SelectionKey key;
	public ReadThread(SelectionKey key){
		this.key = key;
	}
	public void run() {
		String s = read();
		System.out.println("收到:"+s);
		if(s!=null&&!s.equals(""))
		write("you see:"+s);
	}

	public String read(){
		int cnt = 0;
		ByteBuffer bb = ByteBuffer.allocate(4000);
		sc = (SocketChannel)key.channel();
		String rt = "";
		try{
			while(sc.isConnected()&&sc.isOpen()&&(cnt = sc.read(bb))>0){
				String t = new String(bb.array(),"utf-8").trim();
				
				rt = rt+t;
				bb.clear();
			}
			return rt;
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			key.cancel();
		}
		return null;
	}
	public void write(String str){
		try {
			if(sc.isConnected()&&sc.isOpen())
			sc.write(ByteBuffer.wrap(str.getBytes()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally{
			try {
				sc.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

 

 

 

客户端

 

public class NIOClient {

	Selector selector;
	SocketChannel sc ; 
	
	public void init(){
		try {
			selector = Selector.open();
			sc = SocketChannel.open();
			sc.connect(new InetSocketAddress("127.0.0.1",8000));
			sc.configureBlocking(false);
			sc.register(selector, SelectionKey.OP_READ);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void send(String str){
		try {
			if(sc.isConnected()){
				sc.write(ByteBuffer.wrap(str.getBytes()));
			}else{
				System.out.println("没有连接成功");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public String read(){
		ByteBuffer bb = ByteBuffer.allocate(4000);
		try {
			if(selector.select(1000)==1){
				Iterator it = selector.selectedKeys().iterator();
				while(it.hasNext()){
					String rt = "";
					SelectionKey k = (SelectionKey)it.next();
					it.remove();
					int cnt = 0;
					if(k.isReadable()){
						SocketChannel s = (SocketChannel)k.channel();
						while(s.isOpen()&&(cnt=s.read(bb))>0){
							rt += new String(bb.array()).trim();
							bb.clear();
						}
						s.close();
					}
					close();
					k.cancel();
					return rt;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public void close(){
		try {
			sc.close();
			selector.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		NIOClient l = new NIOClient();
		l.init();
		l.send("eee");
		System.out.println(l.read());
	}
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值