当前位置: 首页>>代码示例>>Java>>正文


Java SelectionKey.isReadable方法代码示例

本文整理汇总了Java中java.nio.channels.SelectionKey.isReadable方法的典型用法代码示例。如果您正苦于以下问题:Java SelectionKey.isReadable方法的具体用法?Java SelectionKey.isReadable怎么用?Java SelectionKey.isReadable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.channels.SelectionKey的用法示例。


在下文中一共展示了SelectionKey.isReadable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: run

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
public void run() {
	while (true) {
		try {
			selector.select();
			Iterator<SelectionKey> it = selector.selectedKeys().iterator();
			while (it.hasNext()) {
				SelectionKey k = it.next();
				it.remove();
				if (!k.isValid())
					continue;
				if (k.isReadable()) {
					read(k);
				}
				continue;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 
开发者ID:biancso,项目名称:Mevius-IO,代码行数:22,代码来源:MeviusClient.java

示例2: isReadable

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@Override
protected boolean isReadable(DatagramChannel handle) {
    SelectionKey key = handle.keyFor(selector);

    if ((key == null) || (!key.isValid())) {
        return false;
    }

    return key.isReadable();
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:11,代码来源:NioDatagramAcceptor.java

示例3: run

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
public void run() {
	while (true) {
		try {
			selector.select();
			Iterator<SelectionKey> it = selector.selectedKeys().iterator();
			while (it.hasNext()) {
				SelectionKey k = it.next();
				it.remove();
				if (!k.isValid())
					continue;
				if (k.isAcceptable()) {
					accept(k);
				} else if (k.isReadable()) {
					read(k);
				}
				continue;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 
开发者ID:biancso,项目名称:Mevius-IO,代码行数:24,代码来源:MeviusServer.java

示例4: main

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
//            创建ServerSocketChannel,监听8080端口
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(8080));
//            设置为非阻塞模式
        ssc.configureBlocking(false);
//            为ssc注册选择器
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
//            创建处理器
        Handler handler = new Handler(1024);
        while (true) {
//            等待请求,每次等待阻塞3s,超过3s后线程继续向下运行,如果传入0或者不传参数将一直阻塞
            if (selector.select(3000) == 0) {
                System.out.println("等待请求超时……");
                continue;
            }
            System.out.println("处理请求……");
//            获取待处理的SelectionKey
            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();
                try {
                    // 接收到连接请求时
                    if (key.isAcceptable()) {
                        handler.handleAccept(key);
                    }
//            读数据
                    if (key.isReadable()) {
                        handler.handleRead(key);
                    }
                } catch (IOException ex) {
                    keyIter.remove();
                    continue;
                }
//            处理完后,从待处理的SelectionKey迭代器中移除当前所使用的key
                keyIter.remove();
            }
        }
    }
 
开发者ID:tomoncle,项目名称:JavaStudy,代码行数:41,代码来源:NIOSocketTest.java

示例5: doRunLoop

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private synchronized void doRunLoop() {
  while (running) {
    SelectionKey key = null;
    try {
      // consume as many connections as currently queued to avoid
      // unbridled acceptance of connections that starves the select
      int size = pendingConnections.size();
      for (int i=size; i>0; i--) {
        Connection conn = pendingConnections.take();
        conn.channel.register(readSelector, SelectionKey.OP_READ, conn);
      }
      readSelector.select();

      Iterator<SelectionKey> iter = readSelector.selectedKeys().iterator();
      while (iter.hasNext()) {
        key = iter.next();
        iter.remove();
        if (key.isValid()) {
          if (key.isReadable()) {
            doRead(key);
          }
        }
        key = null;
      }
    } catch (InterruptedException e) {
      if (running) {                      // unexpected -- log it
        LOG.info(Thread.currentThread().getName() + " unexpectedly interrupted", e);
      }
    } catch (IOException ex) {
      LOG.error("Error in Reader", ex);
    }
  }
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:34,代码来源:Server.java

示例6: run

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@Override
public void run() {
    while (true) {
        try {
            if (atomicInteger.get() >= 3) {
                System.out.println("end client");
                break;
            }
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isConnectable()) {
                    handConnect(key);
                } else if (key.isWritable()) {
                    handWrite(key);
                } else if (key.isReadable()) {
                    handRead(key);
                    atomicInteger.incrementAndGet();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
开发者ID:justice-code,项目名称:QiuQiu,代码行数:28,代码来源:Client.java

示例7: processReadySessions

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
private void processReadySessions( Set<SelectionKey> handles )
{
    Iterator<SelectionKey> iterator = handles.iterator();

    while ( iterator.hasNext() )
    {
        SelectionKey key = iterator.next();
        H handle = ( H ) key.channel();
        iterator.remove();

        try
        {
            if ( ( key != null ) && key.isValid() && key.isReadable() )
            {
                readHandle( handle );
            }

            if ( ( key != null ) && key.isValid() && key.isWritable() )
            {
                for ( IoSession session : getManagedSessions().values() )
                {
                    scheduleFlush( ( S ) session );
                }
            }
        }
        catch ( Throwable t )
        {
            ExceptionMonitor.getInstance().exceptionCaught( t );
        }
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:33,代码来源:AbstractPollingConnectionlessIoAcceptor.java

示例8: run

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
public void run() {
	try {
		SelectionKey key;
		log.debug("运行连接请求处理与服务请求接收线程,线程ID:" + Thread.currentThread().getId());
		while (true) {
			selector.select();
			// 首先处理连接请求,并注册连接后的Channel注册到选择器
			// 这种处理连接的方式,可能造成某一个选择器注册的Channel或选择键比其他线程多,导致线程内的繁忙程度不一致
			while ((key = connQueue.poll()) != null) {
				ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
				// 接受一个连接
				SocketChannel sc = ssc.accept();
				sc.configureBlocking(false);
				sc.register(selector, SelectionKey.OP_READ);
				if (log.isDebugEnabled()) {
					log.debug("接受一个客户端连接,处理连接请求的线程ID:" + Thread.currentThread().getId());
				}
			}

			// 再处理服务请求的选择键,并将选择键放入待处理服务队列中
			Set<SelectionKey> keys = selector.selectedKeys();
			Iterator<SelectionKey> it = keys.iterator();
			while (it.hasNext()) {
				SelectionKey keytmp = it.next();
				it.remove();
				if (keytmp.isReadable()) {
					reqQueue.add(keytmp);
				}
			}
		}
	} catch (IOException e) {
		log.error("处理连接请求,并接收服务请求处理异常", e);
	}
}
 
开发者ID:minilynn,项目名称:samplecode,代码行数:35,代码来源:Server.java

示例9: handleKey

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
/**
 * Handle a SelectionKey which was selected
 * Runs unlocked as the caller is single-threaded (or if not, should enforce that handleKey is only called
 * atomically for a given ConnectionHandler)
 *
 * @param key
 */
public static void handleKey(SelectionKey key) {
    ConnectionHandler handler = (ConnectionHandler) key.attachment();
    try {
        if (!key.isValid()) {
            // Key has been cancelled, make sure the socket gets closed
            handler.node.destroy();
            return;
        }
        if (key.isReadable()) {
            // Do a socket read and invoke the connection's receiveBytes message
            int len = handler.channel.read(handler.readBuffer);
            if (len == 0) {
                // Was probably waiting on a write
                return;
            } else if (len == -1) {
                // Socket was closed
                key.cancel();
                handler.node.destroy();
                return;
            }
            // "flip" the buffer - setting the limit to the current position and setting position to 0
            handler.node.receiveMessage(handler.readBuffer);
            // Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative position)
        }
        if (key.isWritable()) {
            handler.writeBytes();
        }
    } catch (Exception e) {
        // This can happen eg if the channel closes while the thread is about to get killed
        // (ClosedByInterruptException), or if handler.connection.receiveBytes throws something
        Log.warn("Error handling SelectionKey: {}", e);
        handler.node.destroy();
    }
}
 
开发者ID:nuls-io,项目名称:nuls,代码行数:42,代码来源:ConnectionHandler.java

示例10: processKey

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void processKey(SelectionKey key) throws IOException {
	if (key.isAcceptable()) {
		processConnection(key);
	} else if (key.isReadable()) {
		processMessage(key);
	}
}
 
开发者ID:roscisz,项目名称:KernelHive,代码行数:8,代码来源:TCPServer.java

示例11: listen

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
/**
 * * // 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 * @throws // IOException
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public void listen() throws Exception { // 轮询访问selector
    while (true) {
        // 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞,
        // 这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时,
        // selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的
        selector.select(); // 获得selector中选中的项的迭代器
        Iterator ite = this.selector.selectedKeys().iterator();
        while (ite.hasNext()) {
            SelectionKey key = (SelectionKey) ite.next(); // 删除已选的key,以防重复处理
            ite.remove(); // 连接事件发生
            if (key.isConnectable()) {
                SocketChannel channel = (SocketChannel) key.channel(); // 如果正在连接,则完成连接
                if (channel.isConnectionPending()) {
                    channel.finishConnect();
                } // 设置成非阻塞
                channel.configureBlocking(false);
                // 在这里可以给服务端发送信息哦
                channel.write(ByteBuffer.wrap(new String("hello server!").getBytes()));
                // 在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。
                channel.register(this.selector, SelectionKey.OP_READ); // 获得了可读的事件
            } else if (key.isReadable()) {
                read(key);
            }
        }
    }
}
 
开发者ID:laidu,项目名称:java-learn,代码行数:32,代码来源:NioClient.java

示例12: handleKey

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
public static void handleKey(SelectionKey key) {
    ConnectionHandler handler = ((ConnectionHandler)key.attachment());
    try {
        if (handler == null)
            return;
        if (!key.isValid()) {
            handler.closeConnection(); // Key has been cancelled, make sure the socket gets closed
            return;
        }
        if (key.isReadable()) {
            // Do a socket read and invoke the connection's receiveBytes message
            int read = handler.channel.read(handler.readBuff);
            if (read == 0)
                return; // Was probably waiting on a write
            else if (read == -1) { // Socket was closed
                key.cancel();
                handler.closeConnection();
                return;
            }
            // "flip" the buffer - setting the limit to the current position and setting position to 0
            handler.readBuff.flip();
            // Use connection.receiveBytes's return value as a check that it stopped reading at the right location
            int bytesConsumed = checkNotNull(handler.connection).receiveBytes(handler.readBuff);
            checkState(handler.readBuff.position() == bytesConsumed);
            // Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative
            // position)
            handler.readBuff.compact();
        }
        if (key.isWritable())
            handler.tryWriteBytes();
    } catch (Exception e) {
        // This can happen eg if the channel closes while the thread is about to get killed
        // (ClosedByInterruptException), or if handler.connection.receiveBytes throws something
        Throwable t = Throwables.getRootCause(e);
        log.warn("Error handling SelectionKey: {} {}", t.getClass().getName(), t.getMessage() != null ? t.getMessage() : "", e);
        handler.closeConnection();
    }
}
 
开发者ID:creativechain,项目名称:creacoinj,代码行数:39,代码来源:ConnectionHandler.java

示例13: handleInput

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
/** 对接收到的key进行处理
 *@description 相关说明
 *@time 创建时间:2017年7月17日下午2:55:56
 *@param key
 *@throws IOException
 *@author dzn
 */
private void handleInput(SelectionKey key) throws IOException{
    if(key.isValid()){
       SocketChannel sc = (SocketChannel)key.channel();
       if(key.isConnectable()){
           if(sc.finishConnect()){
               sc.register(this.selector, SelectionKey.OP_READ);
               this.doWrite(sc);
           }else{
               System.exit(1);//连接失败,进程退出
           }
       }
       
       if(key.isReadable()){
           ByteBuffer bb = ByteBuffer.allocate(1024);
           int readBytes = sc.read(bb);
           if(readBytes > 0){
               bb.flip();
               byte[] bytes = new byte[bb.remaining()];
               bb.get(bytes);
               String body = new String(bytes, "UTF-8");
               System.out.println("Now is " + body);
               this.stop = true;
           }else if(readBytes < 0){
               key.cancel();
               sc.close();
           }else{
               ;// 读到0字节,忽略
           }
       }
    }
}
 
开发者ID:SnailFastGo,项目名称:netty_op,代码行数:39,代码来源:TimeClientHandler.java

示例14: run

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@Override
public void run() {

    while (running) {

        try {
            select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            if (selectionKeys.isEmpty()) {
                continue;
            }

            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {

                final SelectionKey key = iterator.next();
                iterator.remove();

                if (!key.isValid()) {
                    continue;
                }

                if (key.isAcceptable()) {
                    doAccept(key);
                }

                if (key.isConnectable()) {
                    doConnect(key);
                }

                if (key.isValid() && key.isReadable()) {
                    doRead(key);
                }

                if (key.isValid() && key.isWritable()) {
                    doWrite(key);
                }
            }

        } catch (Throwable t) {
            LOGGER.warn("Unexpected exception in the selector loop.", t);

            // 睡眠1S, 防止连续的异常导致cpu消耗
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignore) {
            }
        }
    }
}
 
开发者ID:lemonJun,项目名称:TakinRPC,代码行数:53,代码来源:NioSelectorLoop.java

示例15: startServer

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void startServer() throws Exception{
        //声明一个selector
        selector= SelectorProvider.provider().openSelector();

        //声明一个server socket channel,而且是非阻塞的。
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);

//        InetSocketAddress isa=new InetSocketAddress(InetAddress.getLocalHost(),8000);
        //声明服务器端的端口
        InetSocketAddress isa=new InetSocketAddress(8000);
        //服务器端的socket channel绑定在这个端口。
        ssc.socket().bind(isa);
        //把一个socketchannel注册到一个selector上,同时选择监听的事件,SelectionKey.OP_ACCEPT表示对selector如果
        //监听到注册在它上面的server socket channel准备去接受一个连接,或 有个错误挂起,selector将把OP_ACCEPT加到
        //key ready set 并把key加到selected-key set.
        SelectionKey acceptKey=ssc.register(selector,SelectionKey.OP_ACCEPT);

        for(;;){
            selector.select();
            Set readyKeys=selector.selectedKeys();
            Iterator i=readyKeys.iterator();
            long e=0;
            while (i.hasNext()){
                SelectionKey sk=(SelectionKey)i.next();
                i.remove();

                if(sk.isAcceptable()){
                    doAccept(sk);
                }else if(sk.isValid()&&sk.isReadable()){
                    if(!geym_time_stat.containsKey(((SocketChannel)sk.channel()).socket())){
                        geym_time_stat.put(((SocketChannel)sk.channel()).socket(),System.currentTimeMillis());
                        doRead(sk);
                    }
                }else if(sk.isValid()&&sk.isWritable()){
                    doWrite(sk);
                    e=System.currentTimeMillis();
                    long b=geym_time_stat.remove(((SocketChannel)sk.channel()).socket());
                    System.out.println("spend"+(e-b)+"ms");
                }
            }
        }
    }
 
开发者ID:sean417,项目名称:LearningOfThinkInJava,代码行数:44,代码来源:MultiThreadNIOEchoServer.java


注:本文中的java.nio.channels.SelectionKey.isReadable方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。