當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。