JAVA NIO之选择器

package NotBlockingNetNIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Client {

	public static void main(String[] args) {
		startClient();
	}
	
	public static void startClient() {
		try {
			SocketChannel  sChannel= SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
			//切换到非阻塞模式
			sChannel.configureBlocking(false);
			ByteBuffer buf=ByteBuffer.allocate(1024);
			buf.put("我爱你".getBytes());
			buf.flip();
			sChannel.write(buf);
			buf.clear();
			//关闭
			sChannel.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}

 

package NotBlockingNetNIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class Server {


	public static void main(String[] args) {
		startServer();
	}
	
	public static void startServer() {
		try {
			ServerSocketChannel ssChannel=ServerSocketChannel.open();
			//切换到非阻塞模式
			ssChannel.configureBlocking(false);
			ssChannel.bind(new InetSocketAddress(9898));
			//获取选择器
			Selector selector=Selector.open();
			//将通道注册到选择器上,并且指定"监听接收事件"
			ssChannel.register(selector,SelectionKey.OP_ACCEPT);
			//轮询式的获取选择器上已经“准备就绪”的事件
			while(selector.select()>0) {
				Iterator<SelectionKey> it=  selector.selectedKeys().iterator();
				while(it.hasNext()) {
					//获取准备就绪的事件
					SelectionKey sk=it.next();
					//判断具体是什么事件的准备就绪
					if(sk.isAcceptable()) {
						SocketChannel sChannel=ssChannel.accept();
						//切换到非阻塞式模式
						sChannel.configureBlocking(false);
						//将通道注册到选择器上
						sChannel.register(selector, SelectionKey.OP_READ);
					}else if(sk.isReadable()) {
						SocketChannel sChannel=(SocketChannel) sk.channel();
						//读取数据
						ByteBuffer buf=ByteBuffer.allocate(1024);
						int len=0;
						while((len=sChannel.read(buf))>0) {
							buf.flip();
							System.out.println(new String(buf.array(),0,len));
							buf.clear();
						}
					}
					it.remove();
					
				}
			}
			
			
			
			
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值