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


Java Selector类代码示例

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


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

示例1: run

import java.nio.channels.Selector; //导入依赖的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

示例2: start

import java.nio.channels.Selector; //导入依赖的package包/类
/**
 * 启动client服务
 * @throws IOException
 */
public void start(int port) throws IOException {
    //连接端口
    InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
    System.out.println("Socket Connect To " + inetSocketAddress.getAddress().toString() + ":" + inetSocketAddress.getPort());
    socketChannel = SocketChannel.open(inetSocketAddress);

    //设置非阻塞模式
    socketChannel.configureBlocking(false);

    //写出客户端标识
    sendMessage("I am is Falcon Agent Client");
    if(selector == null){
        //与服务器的连接建立成功
        selector = Selector.open();
    }

}
 
开发者ID:DevopsJK,项目名称:SuitAgent,代码行数:22,代码来源:Client.java

示例3: register

import java.nio.channels.Selector; //导入依赖的package包/类
public FDTSelectionKey register(final UUID fdtsessionID, final SocketChannel channel, final int interests, final SelectionHandler selectionHandler, final FDTKeyAttachement attach) throws InterruptedException {

        if (channel == null) {
            throw new NullPointerException("SocketChannel cannot be null");
        }

        if (selectionHandler == null) {
            throw new NullPointerException("SelectionHanfler cannot be null");
        }

        final Selector sel = getAndRotateSelector();
        final SelectionTask sTask = selTasksMap.get(sel);

        FDTSelectionKey fdtSelectionKey = new FDTSelectionKey(fdtsessionID, channel, interests, selectionHandler, attach, sel, sTask);

        return fdtSelectionKey;
    }
 
开发者ID:fast-data-transfer,项目名称:fdt,代码行数:18,代码来源:SelectionManager.java

示例4: connect

import java.nio.channels.Selector; //导入依赖的package包/类
private void connect(Selector selector) {
	AbstractConnection c = null;
	while ((c = connectQueue.poll()) != null) {
		try {
			SocketChannel channel = (SocketChannel) c.getChannel();
			// 注册 OP_CONNECT(建立连接) 监听与后端连接是否真正建立  // 监听到之后是图-MySql第3步,(TCP连接建立)
			channel.register(selector, SelectionKey.OP_CONNECT, c);
			// 主动连接  阻塞或者非阻塞  // 图-MySql第1步,(TCP连接请求)
			channel.connect(new InetSocketAddress(c.host, c.port));

		} catch (Exception e) {
			LOGGER.error("error:",e);
			c.close(e.toString());
		}
	}
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:17,代码来源:NIOConnector.java

示例5: register

import java.nio.channels.Selector; //导入依赖的package包/类
private void register(Selector selector) {
	AbstractConnection c = null;
	if (registerQueue.isEmpty()) {
		return;
	}
	while ((c = registerQueue.poll()) != null) {
		try {
			// 注册读事件
			((NIOSocketWR) c.getSocketWR()).register(selector);
			// 连接注册,对于FrontendConnection是发送HandshakePacket并异步读取响应
			// 响应为AuthPacket,读取其中的信息,验证用户名密码等信息,如果符合条件
			// 则发送OkPacket
			c.register();
		} catch (Exception e) {
			c.close("register err" + e.toString());
			LOGGER.error("register err", e);
		}
	}
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:20,代码来源:NIOReactor.java

示例6: flush

import java.nio.channels.Selector; //导入依赖的package包/类
@Override
public void flush() throws IOException {
	NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) nioChannel.getAttachment();
	if (att == null) {
		throw new IOException("Key must be cancelled");
	}
	long writeTimeout = att.getTimeout();
	Selector selector = null;
	try {
		selector = pool.get();
	} catch (IOException x) {
		// ignore
	}
	try {
		do {
			if (nioChannel.flush(true, selector, writeTimeout)) {
				break;
			}
		} while (true);
	} finally {
		if (selector != null) {
			pool.put(selector);
		}
	}
}
 
开发者ID:how2j,项目名称:lazycat,代码行数:26,代码来源:UpgradeNioProcessor.java

示例7: stopListening

import java.nio.channels.Selector; //导入依赖的package包/类
/**
 * Close Selector.
 *
 * @see org.apache.catalina.tribes.transport.ReceiverBase#stop()
 */
protected void stopListening() {
    setListen(false);
    Selector selector = this.selector.get();
    if (selector != null) {
        try {
            // Unlock the thread if is is blocked waiting for input
            selector.wakeup();
            // Wait for the receiver thread to finish
            int count = 0;
            while (running && count < 50) {
                Thread.sleep(100);
                count ++;
            }
            if (running) {
                log.warn(sm.getString("NioReceiver.stop.threadRunning"));
            }
            closeSelector();
        } catch (Exception x) {
            log.error("Unable to close cluster receiver selector.", x);
        } finally {
            this.selector.set(null);
        }
    }
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:30,代码来源:NioReceiver.java

示例8: run

import java.nio.channels.Selector; //导入依赖的package包/类
@Override
public void run() {
	final Selector selector = this.selector;
	for (;;) {
		++acceptCount;
		try {
			selector.select( 1000L );
			Set<SelectionKey> keys = selector.selectedKeys();
			try {
				for (SelectionKey key : keys) {
					if (key.isValid() && key.isAcceptable()) {
						accept();							
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Throwable e) {
			LOGGER.warn(getName(), e);
		}
	}
}
 
开发者ID:variflight,项目名称:feeyo-redisproxy,代码行数:25,代码来源:NIOAcceptor.java

示例9: writeToSocket

import java.nio.channels.Selector; //导入依赖的package包/类
/**
 *
 * @param bytebuffer ByteBuffer
 * @param flip boolean
 * @return int
 * @throws IOException
 * TODO Fix non blocking write properly
 */
private synchronized int writeToSocket(ByteBuffer bytebuffer, boolean block, boolean flip) throws IOException {
    if ( flip ) bytebuffer.flip();

    int written = 0;
    NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment();
    if ( att == null ) throw new IOException("Key must be cancelled");
    long writeTimeout = att.getWriteTimeout();
    Selector selector = null;
    try {
        selector = pool.get();
    } catch ( IOException x ) {
        //ignore
    }
    try {
        written = pool.write(bytebuffer, socket, selector, writeTimeout, block);
        //make sure we are flushed
        do {
            if (socket.flush(true,selector,writeTimeout)) break;
        }while ( true );
    }finally {
        if ( selector != null ) pool.put(selector);
    }
    if ( block ) bytebuffer.clear(); //only clear
    return written;
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:34,代码来源:InternalNioOutputBuffer.java

示例10: getSharedSelector

import java.nio.channels.Selector; //导入依赖的package包/类
protected Selector getSharedSelector() throws IOException {
    if (SHARED && SHARED_SELECTOR == null) {
        synchronized ( NioSelectorPool.class ) {
            if ( SHARED_SELECTOR == null )  {
                synchronized (Selector.class) {
                    // Selector.open() isn't thread safe
                    // http://bugs.sun.com/view_bug.do?bug_id=6427854
                    // Affects 1.6.0_29, fixed in 1.7.0_01
                    SHARED_SELECTOR = Selector.open();
                }
                log.info("Using a shared selector for servlet write/read");
            }
        }
    }
    return  SHARED_SELECTOR;
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:17,代码来源:NioSelectorPool.java

示例11: getSharedSelector

import java.nio.channels.Selector; //导入依赖的package包/类
protected Selector getSharedSelector() throws IOException {
	if (SHARED && SHARED_SELECTOR == null) {
		synchronized (NioSelectorPool.class) {
			if (SHARED_SELECTOR == null) {
				synchronized (Selector.class) {
					// Selector.open() isn't thread safe
					// http://bugs.sun.com/view_bug.do?bug_id=6427854
					// Affects 1.6.0_29, fixed in 1.7.0_01
					SHARED_SELECTOR = Selector.open();
				}
				log.info("Using a shared selector for servlet write/read");
			}
		}
	}
	return SHARED_SELECTOR;
}
 
开发者ID:how2j,项目名称:lazycat,代码行数:17,代码来源:NioSelectorPool.java

示例12: TunnelServer

import java.nio.channels.Selector; //导入依赖的package包/类
public TunnelServer(int port, Selector selector) throws IOException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    // ServerSocketChannel.bind() requires API 24
    serverSocketChannel.socket().bind(new InetSocketAddress(Inet4Address.getLoopbackAddress(), port));

    SelectionHandler socketChannelHandler = (selectionKey) -> {
        try {
            ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
            acceptClient(selector, channel);
        } catch (IOException e) {
            Log.e(TAG, "Cannot accept client", e);
        }
    };
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT, socketChannelHandler);
}
 
开发者ID:Genymobile,项目名称:gnirehtet,代码行数:17,代码来源:TunnelServer.java

示例13: UDPConnection

import java.nio.channels.Selector; //导入依赖的package包/类
public UDPConnection(ConnectionId id, Client client, Selector selector, IPv4Header ipv4Header, UDPHeader udpHeader) throws IOException {
    super(id, client);

    networkToClient = new Packetizer(ipv4Header, udpHeader);
    networkToClient.getResponseIPv4Header().swapSourceAndDestination();
    networkToClient.getResponseTransportHeader().swapSourceAndDestination();

    touch();

    SelectionHandler selectionHandler = (selectionKey) -> {
        touch();
        if (selectionKey.isValid() && selectionKey.isReadable()) {
            processReceive();
        }
        if (selectionKey.isValid() && selectionKey.isWritable()) {
            processSend();
        }
        updateInterests();
    };
    channel = createChannel();
    interests = SelectionKey.OP_READ;
    selectionKey = channel.register(selector, interests, selectionHandler);
}
 
开发者ID:Genymobile,项目名称:gnirehtet,代码行数:24,代码来源:UDPConnection.java

示例14: Listener

import java.nio.channels.Selector; //导入依赖的package包/类
public Listener(final String name) throws IOException {
  super(name);
  backlogLength = conf.getInt("hbase.ipc.server.listen.queue.size", 128);
  // Create a new server socket and set to non blocking mode
  acceptChannel = ServerSocketChannel.open();
  acceptChannel.configureBlocking(false);

  // Bind the server socket to the binding addrees (can be different from the default interface)
  bind(acceptChannel.socket(), bindAddress, backlogLength);
  port = acceptChannel.socket().getLocalPort(); //Could be an ephemeral port
  // create a selector;
  selector= Selector.open();

  readers = new Reader[readThreads];
  readPool = Executors.newFixedThreadPool(readThreads,
    new ThreadFactoryBuilder().setNameFormat(
      "RpcServer.reader=%d,bindAddress=" + bindAddress.getHostName() +
      ",port=" + port).setDaemon(true).build());
  for (int i = 0; i < readThreads; ++i) {
    Reader reader = new Reader();
    readers[i] = reader;
    readPool.execute(reader);
  }
  LOG.info(getName() + ": started " + readThreads + " reader(s) listening on port=" + port);

  // Register accepts on the server socket with the selector.
  acceptChannel.register(selector, SelectionKey.OP_ACCEPT);
  this.setName("RpcServer.listener,port=" + port);
  this.setDaemon(true);
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:31,代码来源:RpcServer.java

示例15: addEvent

import java.nio.channels.Selector; //导入依赖的package包/类
public void addEvent(Runnable event) {
    Selector selector = this.selector.get();
    if ( selector != null ) {
        synchronized (events) {
            events.add(event);
        }
        if ( log.isTraceEnabled() ) log.trace("Adding event to selector:"+event);
        if ( isListening() ) selector.wakeup();
    }
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:11,代码来源:NioReceiver.java


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