简单SocketChannel 服务端和客户端连接


服务端代码:

public static void main(String[] args) throws Exception 
	{
		// 创建选择器  
		Selector selector = Selector.open();
		// 打开监听信道  
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		// 与本地端口绑定  
		serverSocketChannel.socket().bind(new InetSocketAddress(9999));
		// 设置为非阻塞模式 
		serverSocketChannel.configureBlocking(false); 
		// 将选择器绑定到监听信道,只有非阻塞信道才可以注册选择器.并在注册过程中指出该信道可以进行Accept操作  
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		
		while (true) 
		{
			// 等待某信道就绪
			int selectInt = selector.select();
			if (selectInt == 0)
				continue;
			// 取得迭代器.selectedKeys()中包含了每个准备好某一I/O操作的信道的SelectionKey
			Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
			while (iterator.hasNext())
			{
				SelectionKey selectionKey = iterator.next();
				// 有客户端连接请求时 
				if (selectionKey.isAcceptable())
					handleAccept(selectionKey);
				// 从客户端读取
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值