Java Code Examples for java.nio.channels.SelectionKey#cancel()
The following examples show how to use
java.nio.channels.SelectionKey#cancel() .
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: NioClientBoss.java From simple-netty-source with Apache License 2.0 | 6 votes |
private static void connect(SelectionKey k) throws IOException { NioClientSocketChannel ch = (NioClientSocketChannel) k.attachment(); try { if (ch.channel.finishConnect()) { k.cancel(); if (ch.timoutTimer != null) { ch.timoutTimer.cancel(); } ch.worker.register(ch, ch.connectFuture); } } catch (ConnectException e) { ConnectException newE = new ConnectException(e.getMessage() + ": " + ch.requestedRemoteAddress); newE.setStackTrace(e.getStackTrace()); throw newE; } }
Example 2
Source File: SocketProcessor.java From java-nio-server with Apache License 2.0 | 6 votes |
private void readFromSocket(SelectionKey key) throws IOException { Socket socket = (Socket) key.attachment(); socket.messageReader.read(socket, this.readByteBuffer); List<Message> fullMessages = socket.messageReader.getMessages(); if(fullMessages.size() > 0){ for(Message message : fullMessages){ message.socketId = socket.socketId; this.messageProcessor.process(message, this.writeProxy); //the message processor will eventually push outgoing messages into an IMessageWriter for this socket. } fullMessages.clear(); } if(socket.endOfStreamReached){ System.out.println("Socket closed: " + socket.socketId); this.socketMap.remove(socket.socketId); key.attach(null); key.cancel(); key.channel().close(); } }
Example 3
Source File: NioConnection.java From cloudstack with Apache License 2.0 | 6 votes |
protected void closeConnection(final SelectionKey key) { if (key != null) { final SocketChannel channel = (SocketChannel)key.channel(); key.cancel(); try { if (channel != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Closing socket " + channel.socket()); } channel.close(); } } catch (final IOException ignore) { s_logger.info("[ignored] channel"); } } }
Example 4
Source File: SelectorTest.java From j2objc with Apache License 2.0 | 6 votes |
public void test_keySetViewsModifications() throws IOException { Set<SelectionKey> keys = selector.keys(); SelectionKey key1 = ssc.register(selector, SelectionKey.OP_ACCEPT); assertTrue(keys.contains(key1)); SocketChannel sc = SocketChannel.open(); sc.configureBlocking(false); SelectionKey key2 = sc.register(selector, SelectionKey.OP_READ); assertTrue(keys.contains(key1)); assertTrue(keys.contains(key2)); key1.cancel(); assertTrue(keys.contains(key1)); selector.selectNow(); assertFalse(keys.contains(key1)); assertTrue(keys.contains(key2)); }
Example 5
Source File: HttpClientImpl.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
synchronized void cancel(SocketChannel e) { SelectionKey key = e.keyFor(selector); if (key != null) { key.cancel(); } selector.wakeup(); }
Example 6
Source File: HTTPReadHandler.java From AdditionsAPI with MIT License | 5 votes |
protected void onComplete(HTTPRequest request, SelectionKey selectionKey) throws IOException { server.timer.removeTimer(selectionKey); selectionKey.cancel(); if(server.debug) { Debug.sayTrue(""); Debug.sayTrue("Request recived from: " + ((SocketChannel)selectionKey.channel()).getRemoteAddress()); Debug.sayTrue(request.toString()); Debug.sayTrue(""); } HTTPContext context = server.getContext(request); ResponseCode code = ResponseCode.OK; if(context == null) { code = ResponseCode.NOT_FOUND; } if(request.method == HTTPRequestMethod.HEAD) { context = null; } this.sendResponse(selectionKey, new HTTPResponse(code, context)); }
Example 7
Source File: AbstractNonBlockingConnectionManager.java From xenqtt with Apache License 2.0 | 5 votes |
final void close(SocketChannel channel, SelectionKey key) { key.cancel(); key.attach(null); try { channel.close(); } catch (IOException ignore) { } }
Example 8
Source File: ProxySetupHandler.java From incubator-gobblin with Apache License 2.0 | 5 votes |
private void connect() throws IOException { if (this.proxy.isOpen()) { if (this.proxy.finishConnect()) { this.proxy.register(this.selector, SelectionKey.OP_WRITE, this); SelectionKey clientKey = this.client.keyFor(this.selector); if (clientKey != null) { clientKey.cancel(); } this.state = HandlerState.WRITING; } else if (this.connectStartTime + Config.PROXY_CONNECT_TIMEOUT_MS < System.currentTimeMillis()) { LOG.warn("Proxy connect timed out for client {}", this.client); closeChannels(); } } }
Example 9
Source File: NetworkSelector.java From tribaltrouble with GNU General Public License v2.0 | 5 votes |
final void cancelKey(SelectionKey key, Handler handler) { Object handler_key = null; if (!deterministic.isPlayback()) { handler_key = key.attachment(); key.cancel(); } handler_key = deterministic.log(handler_key); handler_map.remove(handler_key); }
Example 10
Source File: NIOReactor.java From heisenberg with Apache License 2.0 | 5 votes |
@Override public void run() { final Selector selector = this.selector; for (;;) { ++reactCount; try { selector.select(1000L); register(selector); Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { Object att = key.attachment(); if (att != null && key.isValid()) { int readyOps = key.readyOps(); if ((readyOps & SelectionKey.OP_READ) != 0) { read((NIOConnection) att); } else if ((readyOps & SelectionKey.OP_WRITE) != 0) { write((NIOConnection) att); } else { key.cancel(); } } else { key.cancel(); } } } finally { keys.clear(); } } catch (Throwable e) { LOGGER.warn(name, e); } } }
Example 11
Source File: NioSession.java From jane with GNU Lesser General Public License v3.0 | 5 votes |
/** * Destroy the underlying client socket handle * * @throws IOException any exception thrown by the underlying system calls */ void destroy() throws IOException { SelectionKey key = selKey; if (key != null) key.cancel(); channel.close(); }
Example 12
Source File: HttpClientImpl.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Removes any events with the given {@code interestOps}, and if no * events remaining, cancels the associated SelectionKey. */ void resetInterestOps(int interestOps) { int newOps = 0; Iterator<AsyncEvent> itr = pending.iterator(); while (itr.hasNext()) { AsyncEvent event = itr.next(); int evops = event.interestOps(); if (event.repeating()) { newOps |= evops; continue; } if ((evops & interestOps) != 0) { itr.remove(); } else { newOps |= evops; } } this.interestOps = newOps; SelectionKey key = chan.keyFor(selector); if (newOps == 0) { key.cancel(); } else { key.interestOps(newOps); } }
Example 13
Source File: SelectorThread.java From L2jBrasil with GNU General Public License v3.0 | 5 votes |
private final void closeConnectionImpl(final SelectionKey key, final MMOConnection<T> con) { try { // notify connection con.getClient().onDisconnection(); } finally { try { // close socket and the SocketChannel con.close(); } catch (IOException e) { // ignore, we are closing anyway } finally { con.releaseBuffers(); // clear attachment key.attach(null); // cancel key key.cancel(); } } }
Example 14
Source File: AbstractNonblockingServer.java From incubator-retired-blur with Apache License 2.0 | 5 votes |
/** * Do connection-close cleanup on a given SelectionKey. */ protected void cleanupSelectionKey(SelectionKey key) { // remove the records from the two maps FrameBuffer buffer = (FrameBuffer) key.attachment(); if (buffer != null) { // close the buffer buffer.close(); } // cancel the selection key key.cancel(); }
Example 15
Source File: RCONServer.java From Nemisys with GNU General Public License v3.0 | 5 votes |
private void write(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); synchronized (this.sendQueues) { List<RCONPacket> queue = this.sendQueues.get(channel); ByteBuffer buffer = queue.get(0).toBuffer(); try { channel.write(buffer); queue.remove(0); } catch (IOException exception) { key.cancel(); channel.close(); if (this.rconSessions.contains(channel)) { this.rconSessions.remove(channel); } if (this.sendQueues.containsKey(channel)) { this.sendQueues.remove(channel); } return; } if (queue.isEmpty()) { this.sendQueues.remove(channel); } key.interestOps(SelectionKey.OP_READ); } }
Example 16
Source File: GfxdThriftServerSelector.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * Do connection-close cleanup on a given SelectionKey. */ protected static void cleanupSelectionKey(ClientProcessData data) { // cancel the selection key and close channel data.close(); final SelectionKey key = data.key; if (key != null) { data.key = null; key.cancel(); } }
Example 17
Source File: EchoNIOServer.java From JavaBase with MIT License | 5 votes |
public void start() throws IOException { Selector selector = Selector.open(); //通过OPEN方法来打开一个未绑定的ServerSocketChannel 实例 ServerSocketChannel server = ServerSocketChannel.open(); //将该ServerSocketChannel绑定到指定ip server.bind(new InetSocketAddress(NIOServer.PORT)); //设置是NIO 非阻塞模式 server.configureBlocking(false); //将sever注册到指定Selector对象上 server.register(selector, SelectionKey.OP_ACCEPT); while (!stop) { selector.select(2000); Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectedKeys.iterator(); SelectionKey key; while (it.hasNext()) { key = it.next(); it.remove(); try { handleInput(selector, key); } catch (Exception e) { if (key != null) { key.cancel(); if (key.channel() != null) { key.channel().close(); } } } } } }
Example 18
Source File: RCONServer.java From Jupiter with GNU General Public License v3.0 | 5 votes |
private void write(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); synchronized (this.sendQueues) { List<RCONPacket> queue = this.sendQueues.get(channel); ByteBuffer buffer = queue.get(0).toBuffer(); try { channel.write(buffer); queue.remove(0); } catch (IOException exception) { key.cancel(); channel.close(); if (this.rconSessions.contains(channel)) { this.rconSessions.remove(channel); } if (this.sendQueues.containsKey(channel)) { this.sendQueues.remove(channel); } return; } if (queue.isEmpty()) { this.sendQueues.remove(channel); } key.interestOps(SelectionKey.OP_READ); } }
Example 19
Source File: Tunnel.java From SmartZPN with GNU Lesser General Public License v3.0 | 5 votes |
public void onWritable(SelectionKey key) { try { this.beforeSend(m_SendRemainBuffer);//发送之前,先让子类处理,例如做加密等。 if (this.write(m_SendRemainBuffer, false)) {//如果剩余数据已经发送完毕 key.cancel();//取消写事件。 if (isTunnelEstablished()) { m_BrotherTunnel.beginReceive();//这边数据发送完毕,通知兄弟可以收数据了。 } else { this.beginReceive();//开始接收代理服务器响应数据 } } } catch (Exception e) { this.dispose(); } }
Example 20
Source File: RacyDeregister.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { InetAddress addr = InetAddress.getByName(null); ServerSocketChannel sc = ServerSocketChannel.open(); sc.socket().bind(new InetSocketAddress(addr, 0)); SocketChannel.open(new InetSocketAddress(addr, sc.socket().getLocalPort())); SocketChannel accepted = sc.accept(); accepted.configureBlocking(false); SocketChannel.open(new InetSocketAddress(addr, sc.socket().getLocalPort())); SocketChannel accepted2 = sc.accept(); accepted2.configureBlocking(false); final Selector sel = Selector.open(); SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ); final SelectionKey[] key = new SelectionKey[]{ accepted.register(sel, SelectionKey.OP_READ)}; // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE new Thread() { public void run() { try { for (int k = 0; k < 15; k++) { for (int i = 0; i < 10000; i++) { synchronized (notifyLock) { synchronized (selectorLock) { sel.wakeup(); key[0].interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } notified = false; long beginTime = System.currentTimeMillis(); while (true) { notifyLock.wait(5000); if (notified) { break; } long endTime = System.currentTimeMillis(); if (endTime - beginTime > 5000) { succTermination = false; // wake up main thread doing select() sel.wakeup(); return; } } } } } succTermination = true; // wake up main thread doing select() sel.wakeup(); } catch (Exception e) { System.out.println(e); succTermination = true; // wake up main thread doing select() sel.wakeup(); } } }.start(); // main thread will be doing registering/deregistering with the sel while (true) { sel.select(); if (Boolean.TRUE.equals(succTermination)) { System.out.println("Test passed"); sel.close(); sc.close(); break; } else if (Boolean.FALSE.equals(succTermination)) { System.out.println("Failed to pass the test"); sel.close(); sc.close(); throw new RuntimeException("Failed to pass the test"); } synchronized (selectorLock) { } if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) { synchronized (notifyLock) { notified = true; notifyLock.notify(); key[0].cancel(); sel.selectNow(); key2 = accepted2.register(sel, SelectionKey.OP_READ); key[0] = accepted.register(sel, SelectionKey.OP_READ); } } key2.cancel(); sel.selectedKeys().clear(); } }