Java Code Examples for java.nio.channels.SelectionKey#channel()

The following examples show how to use java.nio.channels.SelectionKey#channel() . 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: NioConnection.java    From cosmic with Apache License 2.0 6 votes vote down vote up
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 2
Source File: SimpleRpcServerResponder.java    From hbase with Apache License 2.0 6 votes vote down vote up
private void doAsyncWrite(SelectionKey key) throws IOException {
  SimpleServerRpcConnection connection = (SimpleServerRpcConnection) key.attachment();
  if (connection == null) {
    throw new IOException("doAsyncWrite: no connection");
  }
  if (key.channel() != connection.channel) {
    throw new IOException("doAsyncWrite: bad channel");
  }

  if (processAllResponses(connection)) {
    try {
      // We wrote everything, so we don't need to be told when the socket is ready for
      // write anymore.
      key.interestOps(0);
    } catch (CancelledKeyException e) {
      /*
       * The Listener/reader might have closed the socket. We don't explicitly cancel the key, so
       * not sure if this will ever fire. This warning could be removed.
       */
      SimpleRpcServer.LOG.warn("Exception while changing ops : " + e);
    }
  }
}
 
Example 3
Source File: MultiThreadNIOEchoServer.java    From LearningOfThinkInJava with Apache License 2.0 6 votes vote down vote up
private void doRead(SelectionKey sk){
    SocketChannel channel=(SocketChannel)sk.channel();
    ByteBuffer bb=ByteBuffer.allocate(8192);
    int len;

    try {
        len=channel.read(bb);
        if(len<0){
            disconnect(sk);
            return;
        }
    }catch (Exception e){
        System.out.println("Fail to read from client");
        e.printStackTrace();
        disconnect(sk);
        return;
    }
    bb.flip();
    tp.execute(new HandleMsg(sk,bb));
}
 
Example 4
Source File: MultipointServer.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void doAccept(final SelectionKey key) throws IOException {
    // we are a server

    // when you are a server, we must first listen for the
    // address of the client before sending data.

    // once they send us their address, we will send our
    // full list of known addresses, followed by the "end"
    // address to signal that we are done.

    // Afterward we will only pulls our heartbeat

    final ServerSocketChannel server = (ServerSocketChannel) key.channel();
    final SocketChannel client = server.accept();
    final InetSocketAddress address = (InetSocketAddress) client.socket().getRemoteSocketAddress();

    client.configureBlocking(false);

    final Session session = new Session(client, address, null);
    session.trace("accept");
    session.state(SelectionKey.OP_READ, State.GREETING);
}
 
Example 5
Source File: NioEchoServer.java    From JavaTutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 接受新的Socket连接。
 * 
 * @param selector 选择器
 * @param selectionKey 
 * @return
 * @throws IOException
 * @throws ClosedChannelException
 */
private static SocketChannel acceptNew(Selector selector,
        SelectionKey selectionKey) throws IOException,
        ClosedChannelException {
    ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
    SocketChannel socketChannel = server.accept();
    if (null != socketChannel) {
        if (logger.isLoggable(Level.INFO)) {
            logger.info("收到一个新的连接,客户端IP:"+socketChannel.socket().getInetAddress().getHostAddress()+",客户端Port:"+socketChannel.socket().getPort());
        }
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
    }
    
    return socketChannel;
}
 
Example 6
Source File: CULNetworkHandlerImpl.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private void processConnect(SelectionKey key) throws Exception {
    SocketChannel ch = (SocketChannel) key.channel();
    if (ch.finishConnect()) {
        key.interestOps(key.interestOps() ^ SelectionKey.OP_CONNECT);
        key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        reconnectInterval = INITIAL_RECONNECT_INTERVAL;
        connected.set(true);
        onConnected();
    }
}
 
Example 7
Source File: EchoServer.java    From netty.book.kor with MIT License 5 votes vote down vote up
/**
 * Read from a client. Enqueue the data on the clients output
 * queue and set the selector to notify on OP_WRITE.
 */
private void doRead(SelectionKey sk) {
    SocketChannel channel = (SocketChannel) sk.channel();
    ByteBuffer bb = ByteBuffer.allocate(8192);
    int len;

    try {
        len = channel.read(bb);
        if (len < 0) {
            disconnect(sk);
            return;
        }
    }
    catch (Exception e) {
        System.out.println("Failed to read from client.");
        e.printStackTrace();
        return;
    }

    // Flip the buffer.
    bb.flip();

    EchoClient echoClient = (EchoClient) sk.attachment();
    echoClient.enqueue(bb);

    // We've enqueued data to be written to the client, we must
    // not set interest in OP_WRITE.
    sk.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
 
Example 8
Source File: SelectorManager.java    From WebSocket-for-Android with Apache License 2.0 5 votes vote down vote up
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 9
Source File: RCONServer.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
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 10
Source File: TCPClientReadThread.java    From game-server with MIT License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public void run() {
	try {
		while (true) {
			selector.select();
			Iterator ite = selector.selectedKeys().iterator();
			while (ite.hasNext()) {

				SelectionKey key = (SelectionKey) ite.next();
				ite.remove();
				if (key.isConnectable()) {
					SocketChannel channel = (SocketChannel) key.channel();
					if (channel.isConnectionPending()) {
						channel.finishConnect();

					}
					channel.configureBlocking(false);
					channel.register(selector, SelectionKey.OP_READ);

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

			}
		}

	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example 11
Source File: ExtendedWorker.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private void clearKey(SelectionKey key) throws IOException {
	if (key.isValid()) {
		SocketChannel socketChannel = (SocketChannel) key.channel();
		socketChannel.close();
		key.attach(null);
		key.cancel();
	}
}
 
Example 12
Source File: ChannelDispatcher.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void selectServerSocketKeys() throws IOException {
    int numSelected = serverSocketSelector.select(timeout);
    if (numSelected == 0) {
        return;
    }

    // for each registered server socket - see if any connections are waiting to be established
    final Iterator<SelectionKey> itr = serverSocketSelector.selectedKeys().iterator();
    while (itr.hasNext()) {
        SelectionKey serverSocketkey = itr.next();
        final SelectableChannel channel = serverSocketkey.channel();
        AbstractChannelReader reader = null;
        if (serverSocketkey.isValid() && serverSocketkey.isAcceptable()) {
            final ServerSocketChannel ssChannel = (ServerSocketChannel) serverSocketkey.channel();
            final SocketChannel sChannel = ssChannel.accept();
            if (sChannel != null) {
                sChannel.configureBlocking(false);
                final SelectionKey socketChannelKey = sChannel.register(socketChannelSelector, SelectionKey.OP_READ);
                final String readerId = sChannel.socket().toString();
                reader = new SocketChannelReader(readerId, socketChannelKey, emptyBuffers, factory);
                final ScheduledFuture<?> readerFuture = executor.scheduleWithFixedDelay(reader, 10L,
                        channelReaderFrequencyMilliseconds.get(), TimeUnit.MILLISECONDS);
                reader.setScheduledFuture(readerFuture);
                socketChannelKey.attach(reader);
            }
        }
        itr.remove(); // do this so that the next select operation returns a positive value; otherwise, it will return 0.
        if (reader != null && LOGGER.isDebugEnabled()) {
            LOGGER.debug(this + " New Connection established.  Server channel: " + channel + " Reader: " + reader);
        }
    }
}
 
Example 13
Source File: Main.java    From netty.book.kor with MIT License 5 votes vote down vote up
private void readOP(SelectionKey key) {
    try {
        SocketChannel socketChannel = (SocketChannel) key.channel();

        buffer.clear();

        int numRead = -1;
        try {
            numRead = socketChannel.read(buffer);
        }
        catch (IOException e) {
            System.err.println("Cannot read error!");
        }

        if (numRead == -1) {
            this.keepDataTrack.remove(socketChannel);
            System.out.println("Connection closed by: " + socketChannel.getRemoteAddress());
            socketChannel.close();
            key.cancel();
            return;
        }

        byte[] data = new byte[numRead];
        System.arraycopy(buffer.array(), 0, data, 0, numRead);
        System.out.println(new String(data, "UTF-8") + " from " + socketChannel.getRemoteAddress());

        // write back to client
        doEchoJob(key, data);
    }
    catch (IOException ex) {
        System.err.println(ex);
    }
}
 
Example 14
Source File: ReactorEchoServerV1.java    From new-bull with MIT License 5 votes vote down vote up
@Override
        public void handle(SelectionKey key) {
            SocketChannel channel = (SocketChannel) key.channel();
            try {
//                System.out.println("decode. readingSize:" + readingSize);
                if (readingSize) {
                    channel.read(sizeBuf);
                    if (!sizeBuf.hasRemaining()) {

                        // consume sizeBuf
                        sizeBuf.flip();
                        size = sizeBuf.getInt();

                        dataBuf = ByteBuffer.allocate(size);
                        readingSize = false;
                    }
                } else {
                    channel.read(dataBuf);
                    if (!dataBuf.hasRemaining()) {

                        dataBuf.flip();
                        String msg = new String(dataBuf.array());

                        new Processor(key.selector(), channel, msg).run();
                        /**
                         *
                         * 这个地方可以优化为在线程池里执行业务操作:
                         *
                         *  threadPool.execute(new Processor(key.selector(), channel, msg));
                         *
                         */
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
Example 15
Source File: ReactorEchoServerV1.java    From new-bull with MIT License 5 votes vote down vote up
@Override
        public void handle(SelectionKey key) {

            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
            Selector selector = key.selector();

            try {
                SocketChannel socketChannel = serverSocketChannel.accept();
//                System.out.println("Got new client:" + socketChannel.getRemoteAddress());
                socketChannel.configureBlocking(false);
                socketChannel.register(selector, SelectionKey.OP_READ, new Decoder());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
Example 16
Source File: AbstractDebugServer.java    From unidbg with Apache License 2.0 5 votes vote down vote up
private void onSelectRead(SelectionKey key) {
    SocketChannel sc = (SocketChannel) key.channel();

    int numRead;
    try {
        numRead = sc.read(input);
    } catch(IOException ex) {
        numRead = -1;
    }

    if (numRead == -1) {
        closeSocketChannel();
    }
}
 
Example 17
Source File: NioConnection.java    From cosmic with Apache License 2.0 5 votes vote down vote up
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: ExtendedWorker.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeOP(SelectionKey key) {
	RapidoidConnection conn = (RapidoidConnection) key.attachment();
	SocketChannel socketChannel = (SocketChannel) key.channel();

	checkOnSameThread();

	touch(conn);

	try {
		synchronized (conn) {
			synchronized (conn.outgoing) {

				if (conn.hasTLS) {
					synchronized (conn.output) {
						conn.tls.wrapToOutgoing();
					}
				}

				writeOp(key, conn, socketChannel);
			}
		}

	} catch (IOException e) {
		close(conn);

	} catch (CancelledKeyException cke) {
		Log.debug("Tried to write on canceled selector key!");
	}
}
 
Example 19
Source File: NetServer.java    From nullpomino with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Receive message(s) from client
 * @param key SelectionKey
 * @throws IOException When something bad happens
 */
private void doRead(SelectionKey key) throws IOException {
	SocketChannel socketChannel = (SocketChannel) key.channel();

	// Clear out our read buffer so it's ready for new data
	if(this.readBuffer == null) {
		this.readBuffer = ByteBuffer.allocate(BUF_SIZE);
	} else {
		this.readBuffer.clear();
	}

	// Attempt to read off the channel
	int numRead;
	try {
		numRead = socketChannel.read(this.readBuffer);
	} catch (IOException e) {
		// The remote forcibly closed the connection, cancel
		// the selection key and close the channel.
		throw e;
	}

	if (numRead == -1) {
		// Remote entity shut the socket down cleanly. Do the
		// same from our end and cancel the channel.
		throw new NetServerDisconnectRequestedException("Connection is closed (numBytesRead is -1)");
	}

	// Process the packet
	readBuffer.flip();

	byte[] bytes = new byte[readBuffer.limit()];
	readBuffer.get(bytes);

	String message = NetUtil.bytesToString(bytes);

	// Previous incomplete packet buffer (null if none are present)
	StringBuilder notCompletePacketBuffer = notCompletePacketMap.remove(socketChannel);

	// The new packet buffer
	StringBuilder packetBuffer = new StringBuilder();
	if(notCompletePacketBuffer != null) packetBuffer.append(notCompletePacketBuffer);
	packetBuffer.append(message);

	int index;
	while((index = packetBuffer.indexOf("\n")) != -1) {
		String msgNow = packetBuffer.substring(0, index);
		processPacket(socketChannel, msgNow);
		packetBuffer = packetBuffer.replace(0, index+1, "");
	}

	// Place new incomplete packet buffer
	if(packetBuffer.length() > 0) {
		notCompletePacketMap.put(socketChannel, packetBuffer);
	}
}
 
Example 20
Source File: NIOConnector.java    From ServletContainer with GNU General Public License v3.0 4 votes vote down vote up
public void read(SelectionKey selectionKey) throws IOException {
    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
    ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
    socketChannel.read(byteBuffer);
    String request = new String(byteBuffer.array()).trim();
}