java.nio.channels.SelectionKey Java Examples
The following examples show how to use
java.nio.channels.SelectionKey.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Listener.java From vespa with Apache License 2.0 | 6 votes |
/** * Perform write operation(s) on channel which is now ready for * writing */ private void performWrite(SelectionKey key) { if (Thread.currentThread().isInterrupted()) { return; } Connection c = (Connection) key.attachment(); try { c.write(); } catch (IOException e) { log.log(Level.FINE, " write failed", e); try { c.close(); } catch (IOException e2) {// ignore } } }
Example #2
Source File: NIOServer.java From yuzhouwan with Apache License 2.0 | 6 votes |
void startServer() throws IOException { // 准备好一个选择器, 监控是否有链接 (OP_ACCEPT) SelectorLoop connectionBell = new SelectorLoop(); // 准备好一个选择器, 监控是否有read事件 (OP_READ) readBell = new SelectorLoop(); // 开启一个server channel来监听 ServerSocketChannel ssc = ServerSocketChannel.open(); // 开启非阻塞模式 ssc.configureBlocking(false); ServerSocket socket = ssc.socket(); socket.bind(new InetSocketAddress("localhost", SOCKET_PORT)); // 给选择器规定好要监听报告的事件, 这个选择器只监听新连接事件 ssc.register(connectionBell.getSelector(), SelectionKey.OP_ACCEPT); new Thread(connectionBell).start(); }
Example #3
Source File: WebSocketServerImpl.java From netbeans with Apache License 2.0 | 6 votes |
private void setHeaders(SelectionKey key , List<String> headerLines, byte[] content ) { if ( headerLines.size() >0 ){ getContext(key).setRequest(headerLines.get(0)); } Map<String,String> result = new HashMap<String, String>(); for (String line : headerLines) { int index = line.indexOf(':'); if ( index != -1 ){ result.put( line.substring( 0, index), line.substring(index+1).trim()); } } getContext(key).setHeaders(result); getContext(key).setContent(content); }
Example #4
Source File: NioSender.java From Tomcat7.0.67 with Apache License 2.0 | 6 votes |
public synchronized void setMessage(byte[] data,int offset, int length) throws IOException { if ( data != null ) { current = data; remaining = length; ackbuf.clear(); if ( writebuf != null ) writebuf.clear(); else writebuf = getBuffer(length); if ( writebuf.capacity() < length ) writebuf = getBuffer(length); //TODO use ByteBuffer.wrap to avoid copying the data. writebuf.put(data,offset,length); //writebuf.rewind(); //set the limit so that we don't write non wanted data //writebuf.limit(length); writebuf.flip(); if (isConnected()) { if (isUdpBased()) dataChannel.register(getSelector(), SelectionKey.OP_WRITE, this); else socketChannel.register(getSelector(), SelectionKey.OP_WRITE, this); } } }
Example #5
Source File: HttpDecodeThread.java From simplewebserver with Apache License 2.0 | 6 votes |
public void doRead(SocketChannel channel, SelectionKey key) throws IOException { if (channel != null && channel.isOpen()) { Map.Entry<HttpRequestDeCoder, HttpResponse> codecEntry = applicationContext.getHttpDeCoderMap().get(channel.socket()); ReadWriteSelectorHandler handler; if (codecEntry == null) { handler = simpleWebServer.getReadWriteSelectorHandlerInstance(channel, key); HttpRequestDeCoder requestDeCoder = new HttpRequestDecoderImpl(requestConfig, applicationContext, handler); codecEntry = new AbstractMap.SimpleEntry<HttpRequestDeCoder, HttpResponse>(requestDeCoder, new SimpleHttpResponse(requestDeCoder.getRequest(), responseConfig)); applicationContext.getHttpDeCoderMap().put(channel.socket(), codecEntry); } else { handler = codecEntry.getKey().getRequest().getHandler(); } LinkedBlockingDeque<RequestEvent> entryBlockingQueue = socketChannelBlockingQueueConcurrentHashMap.get(channel); if (entryBlockingQueue == null) { entryBlockingQueue = new LinkedBlockingDeque<>(); socketChannelBlockingQueueConcurrentHashMap.put(channel, entryBlockingQueue); } entryBlockingQueue.add(new RequestEvent(key, FileCacheKit.generatorRequestTempFile(serverConfig.getPort(), handler.handleRead().array()))); synchronized (this) { this.notify(); } } }
Example #6
Source File: ReceivingClient.java From localization_nifi with Apache License 2.0 | 6 votes |
/** * Process the message that has arrived off the wire. */ @Override void processData(SelectionKey selectionKey, ByteBuffer messageBuffer) throws IOException { byte[] message = new byte[messageBuffer.limit()]; logger.debug("Received message(size=" + message.length + ")"); messageBuffer.get(message); byte lastByteValue = message[message.length - 1]; boolean partialMessage = false; if (lastByteValue != this.endOfMessageByte) { partialMessage = true; selectionKey.attach(1); } else { Integer wasLastPartial = (Integer) selectionKey.attachment(); if (wasLastPartial != null) { if (wasLastPartial.intValue() == 1) { partialMessage = true; selectionKey.attach(0); } } } if (this.messageHandler != null) { this.messageHandler.handle(this.connectedAddress, message, partialMessage); } }
Example #7
Source File: NioReceiver.java From Tomcat8-Source-Read with MIT License | 6 votes |
/** * Sample data handler method for a channel with data ready to read. * @param key A SelectionKey object associated with a channel * determined by the selector to be ready for reading. If the * channel returns an EOF condition, it is closed here, which * automatically invalidates the associated key. The selector * will then de-register the channel on the next select call. * @throws Exception IO error with channel */ protected void readDataFromSocket(SelectionKey key) throws Exception { NioReplicationTask task = (NioReplicationTask) getTaskPool().getRxTask(); if (task == null) { // No threads/tasks available, do nothing, the selection // loop will keep calling this method until a // thread becomes available, the thread pool itself has a waiting mechanism // so we will not wait here. if (log.isDebugEnabled()) log.debug("No TcpReplicationThread available"); } else { // invoking this wakes up the worker thread then returns //add task to thread pool task.serviceChannel(key); getExecutor().execute(task); } }
Example #8
Source File: Client.java From SuitAgent with Apache License 2.0 | 6 votes |
/** * 注册读写事件,轮训发生的事件 * @throws IOException */ public void talk() throws IOException { socketChannel.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE|SelectionKey.OP_READ); while (selector.select() > 0){ Set readyKeys = selector.selectedKeys(); Iterator it = readyKeys.iterator(); while (it.hasNext()){ SelectionKey key = (SelectionKey) it.next(); it.remove(); if(key.isReadable()){ receive(key); } if(shutdown){ key.cancel(); return; } if(key.isWritable()){ send(key); } } } }
Example #9
Source File: XulHttpServer.java From starcor.xul with GNU Lesser General Public License v3.0 | 6 votes |
void reply(XulHttpServerResponse serverResponse) { _response = serverResponse; serverResponse.addHeaderIfNotExists("Content-Type", "text/html") .addHeaderIfNotExists("Connection", "close"); final String transferEncoding = _response.headers.get("Transfer-Encoding"); _sendChunkedData = "chunked".equals(transferEncoding); serverResponse.prepareResponseData(); _responseBuffer = ByteBuffer.wrap(serverResponse.getData(), 0, serverResponse.getDataSize()); try { Selector selector = _server._selector; _socketChannel.register(selector, SelectionKey.OP_WRITE, this); selector.wakeup(); } catch (ClosedChannelException e) { clear(); XulLog.e(TAG, e); } }
Example #10
Source File: NonBlockingServer.java From netty.book.kor with MIT License | 6 votes |
private void read(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(8192); int numRead = -1; try { numRead = channel.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (numRead == -1) { this.dataMap.remove(channel); channel.close(); key.cancel(); return; } byte[] data = new byte[numRead]; System.arraycopy(buffer.array(), 0, data, 0, numRead); // write back to client doEcho(key, data); }
Example #11
Source File: SelectWrite.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public static void main(String[] argv) throws Exception { try (ByteServer server = new ByteServer(); SocketChannel sc = SocketChannel.open(server.address())) { server.acceptConnection(); try (Selector sel = Selector.open()) { sc.configureBlocking(false); sc.register(sel, SelectionKey.OP_WRITE); sel.select(); sel.selectedKeys().clear(); if (sel.select() == 0) { throw new Exception("Select returned zero"); } } } }
Example #12
Source File: NioSelectorLoop.java From TakinRPC with Apache License 2.0 | 5 votes |
private void doWrite(SelectionKey key) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("doWrite:" + key.toString()); } NioChannel channel = (NioChannel) key.attachment(); processor.flush(channel); }
Example #13
Source File: SmackReactor.java From Smack with Apache License 2.0 | 5 votes |
public SelectionKey registerWithSelector(SelectableChannel channel, int ops, ChannelSelectedCallback callback) throws ClosedChannelException { SelectionKeyAttachment selectionKeyAttachment = new SelectionKeyAttachment(callback); registrationLock.lock(); try { selector.wakeup(); return channel.register(selector, ops, selectionKeyAttachment); } finally { registrationLock.unlock(); } }
Example #14
Source File: Connection.java From openhab1-addons with Eclipse Public License 2.0 | 5 votes |
/** * Must be called once the connection is established. * * @throws ClosedChannelException if channel is not open */ private void onConnected() throws ClosedChannelException { this.isChannelConnecting = false; this.lastPingTimeStamp = System.nanoTime(); // Start ping timer synchronized (this.callback.getChannelRegisterSync()) { this.callback.getSelector().wakeup(); // Wakes up a current or next select this.channel.register(this.callback.getSelector(), SelectionKey.OP_READ, this); } }
Example #15
Source File: SelectorImpl.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
private void clearDeferredRegistrations() { synchronized (deferredRegistrations) { int deferredListSize = deferredRegistrations.size(); if (orb.transportDebugFlag) { dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize); } for (int i = 0; i < deferredListSize; i++) { EventHandler eventHandler = (EventHandler)deferredRegistrations.get(i); if (orb.transportDebugFlag) { dprint(".clearDeferredRegistrations: " + eventHandler); } SelectableChannel channel = eventHandler.getChannel(); SelectionKey selectionKey = null; try { if (orb.transportDebugFlag) { dprint(".clearDeferredRegistrations:close channel == " + channel); dprint(".clearDeferredRegistrations:close channel class == " + channel.getClass().getName()); } channel.close(); selectionKey = eventHandler.getSelectionKey(); if (selectionKey != null) { selectionKey.cancel(); selectionKey.attach(null); } } catch (IOException ioEx) { if (orb.transportDebugFlag) { dprint(".clearDeferredRegistrations: ", ioEx); } } } deferredRegistrations.clear(); } }
Example #16
Source File: AbstractSelectableChannel.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
private SelectionKey findKey(Selector sel) { synchronized (keyLock) { if (keys == null) return null; for (int i = 0; i < keys.length; i++) if ((keys[i] != null) && (keys[i].selector() == sel)) return keys[i]; return null; } }
Example #17
Source File: NioConnection.java From cloudstack with Apache License 2.0 | 5 votes |
protected void logTrace(final Exception e, final SelectionKey key, final int loc) { if (s_logger.isTraceEnabled()) { Socket socket = null; if (key != null) { final SocketChannel ch = (SocketChannel)key.channel(); if (ch != null) { socket = ch.socket(); } } s_logger.trace("Location " + loc + ": Socket " + socket + " closed on read. Probably -1 returned."); } }
Example #18
Source File: SelectorManager.java From IoTgo_Android_App with MIT License | 5 votes |
public void dumpKeyState(List<Object> dumpto) { Selector selector=_selector; Set<SelectionKey> keys = selector.keys(); dumpto.add(selector + " keys=" + keys.size()); for (SelectionKey key: keys) { if (key.isValid()) dumpto.add(key.attachment()+" iOps="+key.interestOps()+" rOps="+key.readyOps()); else dumpto.add(key.attachment()+" iOps=-1 rOps=-1"); } }
Example #19
Source File: Reactor.java From jlibs with Apache License 2.0 | 5 votes |
void unregister(TCPServer server){ if(DEBUG) println(server+".unregister"); servers.remove(server); SelectionKey key = server.selectable.keyFor(selector); if(key!=null && key.isValid()) key.cancel(); }
Example #20
Source File: ReadAfterConnect.java From hottub with GNU General Public License v2.0 | 5 votes |
public static void main(String[] argv) throws Exception { try (ByteServer server = new ByteServer(); SocketChannel sc = SocketChannel.open(server.address())) { server.acceptConnection(); try (Selector sel = Selector.open()) { sc.configureBlocking(false); sc.register(sel, SelectionKey.OP_READ); // Previously channel would get selected here, although there is nothing to read if (sel.selectNow() != 0) throw new Exception("Select returned nonzero value"); } } }
Example #21
Source File: AbstractSocketHandler.java From localization_nifi with Apache License 2.0 | 5 votes |
@Override public void run() { try { while (AbstractSocketHandler.this.rootChannel != null && AbstractSocketHandler.this.rootChannel.isOpen() && AbstractSocketHandler.this.selector.isOpen()) { if (AbstractSocketHandler.this.selector.isOpen() && AbstractSocketHandler.this.selector.select(10) > 0) { Iterator<SelectionKey> keys = AbstractSocketHandler.this.selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey selectionKey = keys.next(); keys.remove(); if (selectionKey.isValid()) { if (selectionKey.isAcceptable()) { this.accept(selectionKey); } else if (selectionKey.isReadable()) { this.read(selectionKey); } else if (selectionKey.isConnectable()) { this.connect(selectionKey); } } } } } } catch (Exception e) { logger.error("Exception in socket listener loop", e); } logger.debug("Exited Listener loop."); AbstractSocketHandler.this.stop(); }
Example #22
Source File: SctpChannelImpl.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
@Override public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) { int newOps = 0; if ((ops & SelectionKey.OP_READ) != 0) newOps |= Net.POLLIN; if ((ops & SelectionKey.OP_WRITE) != 0) newOps |= Net.POLLOUT; if ((ops & SelectionKey.OP_CONNECT) != 0) newOps |= Net.POLLCONN; sk.selector.putEventOps(sk, newOps); }
Example #23
Source File: MultiplexerTimeServer.java From JavaInterview with Apache License 2.0 | 5 votes |
/** * 初始化多路复用器 * * @param port * * */ public MultiplexerTimeServer(int port) { try { this.selector = Selector.open(); this.serverSocketChannel = ServerSocketChannel.open(); this.serverSocketChannel.configureBlocking(false); this.serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024); this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT); System.out.println("The Multiplexer Time Server is start on port:" + port); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } }
Example #24
Source File: SocketChannelWithTimeouts.java From jmeter-plugins with Apache License 2.0 | 5 votes |
protected SocketChannelWithTimeouts() throws IOException { super(null); log.debug("Creating socketChannel"); selector = Selector.open(); socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); channelKey = socketChannel.register(selector, SelectionKey.OP_CONNECT); }
Example #25
Source File: Connection.java From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void doNextWriteCheck() { //检查是否正在写,看CAS更新writing值是否成功 if ( !writing.compareAndSet(false, true) ) { return; } try { //利用缓存队列和写缓冲记录保证写的可靠性,返回true则为全部写入成功 boolean noMoreData = write0(); //如果全部写入成功而且写入队列为空(有可能在写入过程中又有新的Bytebuffer加入到队列),则取消注册写事件 //否则,继续注册写事件 if ( noMoreData && writeQueue.isEmpty() ) { if ( (processKey.isValid() && (processKey.interestOps() & SelectionKey.OP_WRITE) != 0)) { disableWrite(); } } else { if ((processKey.isValid() && (processKey.interestOps() & SelectionKey.OP_WRITE) == 0)) { enableWrite(false); } } } catch (IOException e) { if ( LOGGER.isDebugEnabled() ) { LOGGER.debug("caught err:", e); } close("err:" + e); } finally { //CAS RESET writing.set(false); } }
Example #26
Source File: ReadAfterConnect.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] argv) throws Exception { try (ByteServer server = new ByteServer(); SocketChannel sc = SocketChannel.open(server.address())) { server.acceptConnection(); try (Selector sel = Selector.open()) { sc.configureBlocking(false); sc.register(sel, SelectionKey.OP_READ); // Previously channel would get selected here, although there is nothing to read if (sel.selectNow() != 0) throw new Exception("Select returned nonzero value"); } } }
Example #27
Source File: SctpChannelImpl.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
@Override public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) { int newOps = 0; if ((ops & SelectionKey.OP_READ) != 0) newOps |= Net.POLLIN; if ((ops & SelectionKey.OP_WRITE) != 0) newOps |= Net.POLLOUT; if ((ops & SelectionKey.OP_CONNECT) != 0) newOps |= Net.POLLCONN; sk.selector.putEventOps(sk, newOps); }
Example #28
Source File: SelectorImpl.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
public void registerForEvent(EventHandler eventHandler) { if (orb.transportDebugFlag) { dprint(".registerForEvent: " + eventHandler); } if (isClosed()) { if (orb.transportDebugFlag) { dprint(".registerForEvent: closed: " + eventHandler); } return; } if (eventHandler.shouldUseSelectThreadToWait()) { synchronized (deferredRegistrations) { deferredRegistrations.add(eventHandler); } if (! selectorStarted) { startSelector(); } selector.wakeup(); return; } switch (eventHandler.getInterestOps()) { case SelectionKey.OP_ACCEPT : createListenerThread(eventHandler); break; case SelectionKey.OP_READ : createReaderThread(eventHandler); break; default: if (orb.transportDebugFlag) { dprint(".registerForEvent: default: " + eventHandler); } throw new RuntimeException( "SelectorImpl.registerForEvent: unknown interest ops"); } }
Example #29
Source File: SelectorManager.java From WebSocket-for-Android with Apache License 2.0 | 5 votes |
private void renewSelector() { try { synchronized (this) { Selector selector=_selector; if (selector==null) return; final Selector new_selector = Selector.open(); for (SelectionKey k: selector.keys()) { if (!k.isValid() || k.interestOps()==0) continue; final SelectableChannel channel = k.channel(); final Object attachment = k.attachment(); if (attachment==null) addChange(channel); else addChange(channel,attachment); } _selector.close(); _selector=new_selector; } } catch(IOException e) { throw new RuntimeException("recreating selector",e); } }
Example #30
Source File: Tunnel.java From SmartProxy with GNU General Public License v3.0 | 5 votes |
public void connect(InetSocketAddress destAddress) throws Exception{ if(LocalVpnService.Instance.protect(m_InnerChannel.socket())){//����socket����vpn m_DestAddress=destAddress; m_InnerChannel.register(m_Selector, SelectionKey.OP_CONNECT,this);//ע�������¼� m_InnerChannel.connect(m_ServerEP);//����Ŀ�� }else { throw new Exception("VPN protect socket failed."); } }