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


Java SelectionKey.isConnectable方法代码示例

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


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

示例1: process

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void process() {
    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
    while (it.hasNext()) {
        SelectionKey key = it.next();
        it.remove();
        if (!key.isValid()) {
            continue;
        }
        ChannelHandler handler = (ChannelHandler) key.attachment();
        if (key.isAcceptable()) {
            handler.accept(key);
        } else if (key.isConnectable()) {
            handler.connect(key);
        } else if (key.isReadable()) {
            handler.read(key);
        } else if (key.isWritable()) {
            handler.write(key);
        }
    }
}
 
开发者ID:xiaoma20082008,项目名称:mysql-protocol,代码行数:21,代码来源:Multiplexer.java

示例2: handleKey

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

        if (key.isValid() && key.isConnectable()) {
            //out node
            addOutNode(key);
        } else if (key.isValid() && key.isAcceptable()) {
            // in Node
            addInNode(key);
        } else {
            // read or write
            ConnectionHandler handler = (ConnectionHandler) key.attachment();
            if (handler != null) {
                ConnectionHandler.handleKey(key);
            }
        }
    }
 
开发者ID:nuls-io,项目名称:nuls,代码行数:17,代码来源:ConnectionManager.java

示例3: working

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
/**
 * 主要执行程序
 */
public void working() throws IOException {
    while (true) {
        if (!selector.isOpen()) break;
        //通过Selector得到已经准备好的事件。如果当前没有任何事件准备就绪,这里就会阻塞
        selector.select();
        Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
        //主要处理两个事件,首先是表示连接就绪的Connct事件(由connect()函数处理)以及表示通道可读的Read事件(由read()函数处理)
        while (ite.hasNext()) {
            SelectionKey key = ite.next();
            ite.remove();
            // 连接事件发生
            if (key.isConnectable()) {
                connect(key);

            } else if (key.isReadable()) {
                read(key);

            }
        }
    }
}
 
开发者ID:zhangboqing,项目名称:multithread,代码行数:25,代码来源:NIOEchoClient.java

示例4: start0

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void start0() throws IOException {
    while (!closed) {

        processQueues();
        selector.select();

        if (selector.selectedKeys().isEmpty()) {
            processQueues();
        }

        for (Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext(); ) {
            SelectionKey key = i.next();
            i.remove();

            if (key.isConnectable()) {
                SocketChannel socketChannel = (SocketChannel) key.channel();
                socketChannel.finishConnect();
                LOG.info("SocketChannel connected.");
            }

            if (key.isReadable()) {
                this.socketChannelReader.readFromKey(key);
            }
        }
    }
}
 
开发者ID:yiding-he,项目名称:java-nio-test,代码行数:27,代码来源:SocketChannelClientHandler.java

示例5: handle

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void handle(SelectionKey key) {
	SocketChannel channel = (SocketChannel) key.channel();
	if (key.isConnectable()) {
		try {
			if (channel.finishConnect()) {
				//connect finish
				this.logger.info("[Connecter] finish connect " + channel.getRemoteAddress().toString());
				IoWorker worker = this.workers.get(workersIndex);
				worker.dispatch(new JobBean(channel, this.chanToParam.get(channel)));
				workersIndex = (workersIndex + 1) % workers.size();
			}
		} catch (IOException e) {
			this.logger.info("[Connecter] finish connect error : " + e.toString());
			ClientParam clientParam = this.chanToParam.get(channel);
			if (clientParam.getOnConnectError() != null) {
				clientParam.getOnConnectError().onConnectError(e);
			}
			this.chanToParam.remove(channel);
			try {
				channel.close();
			} catch (IOException e1) {
				// already close
			}
		}
	}
}
 
开发者ID:luohaha,项目名称:LightComm4J,代码行数:27,代码来源:Connector.java

示例6: run

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@Override
public void run() {
    final Selector tSelector = this.selector;
    for (; ; ) {
        try {
            tSelector.select(1000L);
            connect(tSelector);
            Set<SelectionKey> keys = tSelector.selectedKeys();
            try {
                for (SelectionKey key : keys) {
                    Object att = key.attachment();
                    if (att != null && key.isValid() && key.isConnectable()) {
                        finishConnect(key, att);
                    } else {
                        key.cancel();
                    }
                }
            } finally {
                keys.clear();
            }
        } catch (Exception e) {
            LOGGER.info(name, e);
        }
    }
}
 
开发者ID:actiontech,项目名称:dble,代码行数:26,代码来源:NIOConnector.java

示例7: run

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@Override
public void run() {
	final Selector tSelector = this.selector;
	for (;;) {
		++connectCount;
		try {
			// 查看有无连接就绪 阻塞的
			tSelector.select(1000L);
			connect(tSelector);
			Set<SelectionKey> keys = tSelector.selectedKeys();
			try {
				for (SelectionKey key : keys) {
					Object att = key.attachment();
					if (att != null && key.isValid() && key.isConnectable()) {
						finishConnect(key, att);
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Exception e) {
			LOGGER.warn(name, e);
		}
	}
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:28,代码来源:NIOConnector.java

示例8: 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

示例9: 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

示例10: 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

示例11: run

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@Override
public void run() {
	final Selector selector = this.selector;
	for (;;) {
		++connectCount;
		try {
			//查看有无连接就绪
			selector.select( 1000L );
			connect(selector);
			Set<SelectionKey> keys = selector.selectedKeys();
			try {
				for (SelectionKey key: keys) {
					Object att = key.attachment();
					if (att != null && key.isValid() && key.isConnectable()) {
						finishConnect(key, att);
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Exception e) {
			LOGGER.warn(name, e);
		}
	}
}
 
开发者ID:variflight,项目名称:feeyo-redisproxy,代码行数:28,代码来源:NIOConnector.java

示例12: _connect

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void _connect() throws IOException {
    // Continuous loop that is only supposed to end when "close" is called.

    selector.select();
    Set<SelectionKey> keys = selector.selectedKeys();
    Iterator<SelectionKey> i = keys.iterator();

    while (i.hasNext()) {
        SelectionKey key = i.next();
        i.remove();
        if (key.isConnectable()) {
            if (socketChannel.isConnectionPending()) {
                socketChannel.finishConnect();
            }
            socketChannel.register(selector, SelectionKey.OP_READ);
            _writeHandshake();
        }
        if (key.isReadable()) {
            try {
                _read();
            } catch (NoSuchAlgorithmException nsa) {
                this.onError(nsa);
            }
        }
    }

}
 
开发者ID:sinhaDroid,项目名称:BlogBookApp,代码行数:28,代码来源:WebSocket.java

示例13: 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

示例14: process

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
/**
 * State machine to send data
 * @param key SelectionKey
 * @return boolean
 * @throws IOException
 */
public boolean process(SelectionKey key, boolean waitForAck) throws IOException {
    int ops = key.readyOps();
    key.interestOps(key.interestOps() & ~ops);
    //in case disconnect has been called
    if ((!isConnected()) && (!connecting)) throw new IOException("Sender has been disconnected, can't selection key.");
    if ( !key.isValid() ) throw new IOException("Key is not valid, it must have been cancelled.");
    if ( key.isConnectable() ) {
        if ( socketChannel.finishConnect() ) {
            completeConnect();
            if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            return false;
        } else  {
            //wait for the connection to finish
            key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT);
            return false;
        }//end if
    } else if ( key.isWritable() ) {
        boolean writecomplete = write(key);
        if ( writecomplete ) {
            //we are completed, should we read an ack?
            if ( waitForAck ) {
                //register to read the ack
                key.interestOps(key.interestOps() | SelectionKey.OP_READ);
            } else {
                //if not, we are ready, setMessage will reregister us for another write interest
                //do a health check, we have no way of verify a disconnected
                //socket since we don't register for OP_READ on waitForAck=false
                read(key);//this causes overhead
                setRequestCount(getRequestCount()+1);
                return true;
            }
        } else {
            //we are not complete, lets write some more
            key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);
        }//end if
    } else if ( key.isReadable() ) {
        boolean readcomplete = read(key);
        if ( readcomplete ) {
            setRequestCount(getRequestCount()+1);
            return true;
        } else {
            key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        }//end if
    } else {
        //unknown state, should never happen
        log.warn("Data is in unknown state. readyOps="+ops);
        throw new IOException("Data is in unknown state. readyOps="+ops);
    }//end if
    return false;
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:57,代码来源:NioSender.java

示例15: start

import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
public void start() {
	ServerSocketChannel ssc = null;
	try {
		selector = Selector.open();
		ssc = ServerSocketChannel.open();
		ssc.socket().bind(new InetSocketAddress(port));
		ssc.configureBlocking(false);
		ssc.register(selector, SelectionKey.OP_ACCEPT);
		log.info("start success,listen on port " + port);

		while (true) {
			/**
			 * select操作执行时其他线程register,将会阻塞.可以在任意时刻关闭通道或者取消键.
			 * 因为select操作并未对Key.cancell()同步,因此有可能再selectedKey中出现的key是已经被取消的.
			 * 这一点需要注意.需要校验:key.isValid() && key.isReadable()
			 */
			if (selector.select(500) == 0) {
				continue;
			}
			Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
			while (iter.hasNext()) {
				SelectionKey key = iter.next();
				if (key.isAcceptable()) {
					log.info("server recieve an accept");
					handleAccept(key);
				}
				if (key.isValid() && key.isReadable()) {
					log.info("server recieve a read");
					handleRead(key);
				}
				if (key.isWritable() && key.isValid()) {
					log.info("server recieve a write");
					handleWrite(key);
				}
				if (key.isConnectable()) {
					log.info("server recieve a isConnectable = true");
				}
				if (!key.isValid()){
					key.cancel();
					log.error("");
				}
				iter.remove();
			}
		}

	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
开发者ID:spafka,项目名称:spark_deep,代码行数:50,代码来源:NioServer.java


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