Java Code Examples for java.nio.channels.SocketChannel#register()

The following examples show how to use java.nio.channels.SocketChannel#register() . 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: TcpConnection.java    From RuinsOfRevenge with MIT License 6 votes vote down vote up
public SelectionKey accept (Selector selector, SocketChannel socketChannel) throws IOException {
	writeBuffer.clear();
	readBuffer.clear();
	readBuffer.flip();
	currentObjectLength = 0;
	try {
		this.socketChannel = socketChannel;
		socketChannel.configureBlocking(false);
		Socket socket = socketChannel.socket();
		socket.setTcpNoDelay(true);

		selectionKey = socketChannel.register(selector, SelectionKey.OP_READ);

		if (DEBUG) {
			debug("kryonet", "Port " + socketChannel.socket().getLocalPort() + "/TCP connected to: "
				+ socketChannel.socket().getRemoteSocketAddress());
		}

		lastReadTime = lastWriteTime = System.currentTimeMillis();

		return selectionKey;
	} catch (IOException ex) {
		close();
		throw ex;
	}
}
 
Example 2
Source File: MultiThreadNIOEchoServer.java    From cs-summary-reflection with Apache License 2.0 6 votes vote down vote up
/**
 * @author 梦境迷离
 * @description 与客户端建立链接
 * @time 2018年3月28日
 */
private void doAccept(SelectionKey sk) {
    ServerSocketChannel server = (ServerSocketChannel) sk.channel();
    SocketChannel clientChannel;
    try {
        clientChannel = server.accept();
        // 设置为非阻塞的
        clientChannel.configureBlocking(false);
        // 注册可读
        SelectionKey clientKey = clientChannel.register(selector, SelectionKey.OP_READ);
        // 将客户端实例作为附件,附加到表示这个连接 的SelectionKey上,这样整个连接处理都可以共享这个客户端
        EchoClient echoClient = new EchoClient();
        clientKey.attach(echoClient);
        // 获取客户端的地址
        InetAddress clientAddress = clientChannel.socket().getInetAddress();
        System.out.println("Accepted connection from " + clientAddress.getHostAddress() + ".");
    } catch (Exception e) {
        System.out.println("Failed to accept new client.");
        e.printStackTrace();
    }
}
 
Example 3
Source File: NonBlockingServerWithOffLoopTasks.java    From tls-channel with MIT License 6 votes vote down vote up
private static void handleNewConnection(
    SSLContext sslContext, Selector selector, ServerSocketChannel serverChannel)
    throws IOException {
  // accept new connection
  SocketChannel rawChannel = serverChannel.accept();
  rawChannel.configureBlocking(false);

  // wrap raw channel in TlsChannel
  TlsChannel tlsChannel =
      ServerTlsChannel.newBuilder(rawChannel, sslContext).withRunTasks(false).build();

  /*
   * Wrap raw channel with a TlsChannel. Note that the raw channel is registered in the selector
   * and the TlsChannel put as an attachment register the channel for reading, because TLS
   * connections are initiated by clients.
   */
  SelectionKey newKey = rawChannel.register(selector, SelectionKey.OP_READ);
  newKey.attach(tlsChannel);
}
 
Example 4
Source File: SelectorThread.java    From L2jBrasil with GNU General Public License v3.0 6 votes vote down vote up
private final void acceptConnection(final SelectionKey key, MMOConnection<T> con)
{
    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
    SocketChannel sc;

    try
    {
        while ((sc = ssc.accept()) != null)
        {
            if (_acceptFilter == null || _acceptFilter.accept(sc))
            {
                sc.configureBlocking(false);
                SelectionKey clientKey = sc.register(_selector, SelectionKey.OP_READ);
                con = new MMOConnection<T>(this, sc.socket(), clientKey);
                con.setClient(_clientFactory.create(con));
                clientKey.attach(con);
            }
            else
                sc.socket().close();
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
 
Example 5
Source File: Selector.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Register the nioSelector with an existing channel
 * Use this on server-side, when a connection is accepted by a different thread but processed by the Selector
 * Note that we are not checking if the connection id is valid - since the connection already exists
 */
public String register(SocketChannel channel, PortType portType) throws IOException {
  Socket socket = channel.socket();
  String connectionId = generateConnectionId(channel);
  SelectionKey key = channel.register(nioSelector, SelectionKey.OP_READ);
  Transmission transmission;
  try {
    transmission =
        createTransmission(connectionId, key, socket.getInetAddress().getHostName(), socket.getPort(), portType,
            SSLFactory.Mode.SERVER);
  } catch (IOException e) {
    logger.error("IOException on transmission creation ", e);
    socket.close();
    channel.close();
    throw e;
  }
  key.attach(transmission);
  this.keyMap.put(connectionId, key);
  numActiveConnections.set(this.keyMap.size());
  return connectionId;
}
 
Example 6
Source File: MonitorThread.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void acceptNewDebugger(Debugger dbg, ServerSocketChannel acceptChan)
        throws IOException {

    synchronized (mClientList) {
        SocketChannel chan;

        if (acceptChan == null)
            chan = dbg.accept();
        else
            chan = dbg.accept(acceptChan);

        if (chan != null) {
            chan.socket().setTcpNoDelay(true);

            wakeup();

            try {
                chan.register(mSelector, SelectionKey.OP_READ, dbg);
            } catch (IOException ioe) {
                // failed, drop the connection
                dbg.closeData();
                throw ioe;
            } catch (RuntimeException re) {
                // failed, drop the connection
                dbg.closeData();
                throw re;
            }
        } else {
            Log.w("ddms", "ignoring duplicate debugger");
            // new connection already closed
        }
    }
}
 
Example 7
Source File: SocketConnection.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public SocketInputStream(SocketChannel socket) throws IOException {
    this.socket = socket;
    selector = Selector.open();
    socket.register(selector, SelectionKey.OP_READ);
    buffer = ByteBuffer.allocateDirect(4096);
    buffer.limit(0);
}
 
Example 8
Source File: Main.java    From netty.book.kor with MIT License 5 votes vote down vote up
private void acceptOP(SelectionKey key, Selector selector) throws IOException {

        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
        SocketChannel socketChannel = serverChannel.accept();
        socketChannel.configureBlocking(false);

        System.out.println("Incoming connection from: " + socketChannel.getRemoteAddress());

        // write an welcome message
        socketChannel.write(ByteBuffer.wrap("Hello!\n".getBytes("UTF-8")));

        // register channel with selector for further I/O
        keepDataTrack.put(socketChannel, new ArrayList<byte[]>());
        socketChannel.register(selector, SelectionKey.OP_READ);
    }
 
Example 9
Source File: NIOServer.java    From JavaBase with MIT License 5 votes vote down vote up
private void register(Selector selector, ServerSocketChannel server, SelectionKey sk)
    throws IOException {
  //调用accept方法,产生服务器端的SocketChannel
  SocketChannel sc = server.accept();
  sc.configureBlocking(false);//NIO模式
  sc.register(selector, SelectionKey.OP_READ);//注册到selector上
  sk.interestOps(SelectionKey.OP_ACCEPT);//将sk对应的Channel设置成准备接受其他请求
}
 
Example 10
Source File: Driver.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
ChannelHandler(SocketChannel socket, int ops, Transport transport) throws IOException {
    this.socket = socket;
    socket.configureBlocking(false);
    key = socket.register(selector, ops, this);
    this.transport = transport;
    transport.setContext(this);
}
 
Example 11
Source File: MultiThreadNIOEchoClient.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
/**
 * @author 梦境迷离
 * @description 连接
 * @time 2018年3月28日
 */
private void connect(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    // 如果正在连接,则完成连接
    if (channel.isConnectionPending()) {
        channel.finishConnect();
    }
    channel.configureBlocking(false);
    channel.write(ByteBuffer.wrap("Hello Server !\r\n".getBytes()));
    // 注册读事件为感兴趣的事件
    channel.register(this.selector, SelectionKey.OP_READ);
}
 
Example 12
Source File: LotsOfCancels.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 13
Source File: Server.java    From RDFS with Apache License 2.0 4 votes vote down vote up
private boolean processResponse(LinkedList<Call> responseQueue,
                                boolean inHandler) throws IOException {
  boolean error = true;
  boolean done = false;       // there is more data for this channel.
  int numElements = 0;
  Call call = null;
  try {
    synchronized (responseQueue) {
      //
      // If there are no items for this channel, then we are done
      //
      numElements = responseQueue.size();
      if (numElements == 0) {
        error = false;
        return true;              // no more data for this channel.
      }
      //
      // Extract the first call
      //
      call = responseQueue.removeFirst();
      SocketChannel channel = call.connection.channel;
      if (LOG.isDebugEnabled()) {
        LOG.debug(getName() + ": responding to #" + call.id + " from " +
                  call.connection);
      }
      //
      // Send as much data as we can in the non-blocking fashion
      //
      int numBytes = channelWrite(channel, call.response);
      if (numBytes < 0) {
        return true;
      }
      if (!call.response.hasRemaining()) {
        call.connection.decRpcCount();
        if (numElements == 1) {    // last call fully processes.
          done = true;             // no more data for this channel.
        } else {
          done = false;            // more calls pending to be sent.
        }
        if (LOG.isDebugEnabled()) {
          LOG.debug(getName() + ": responding to #" + call.id + " from " +
                    call.connection + " Wrote " + numBytes + " bytes.");
        }
      } else {
        //
        // If we were unable to write the entire response out, then
        // insert in Selector queue.
        //
        call.connection.responseQueue.addFirst(call);

        if (inHandler) {
          // set the serve time when the response has to be sent later
          call.timestamp = System.currentTimeMillis();

          incPending();
          try {
            // Wakeup the thread blocked on select, only then can the call
            // to channel.register() complete.
            writeSelector.wakeup();
            channel.register(writeSelector, SelectionKey.OP_WRITE, call);
          } catch (ClosedChannelException e) {
            //Its ok. channel might be closed else where.
            done = true;
          } finally {
            decPending();
          }
        }
        if (LOG.isDebugEnabled()) {
          LOG.debug(getName() + ": responding to #" + call.id + " from " +
                    call.connection + " Wrote partial " + numBytes +
                    " bytes.");
        }
      }
      error = false;              // everything went off well
    }
  } finally {
    if (error && call != null) {
      LOG.warn(getName()+", call " + call + ": output error");
      done = true;               // error. no more data for this channel.
      closeConnection(call.connection);
    }
  }
  return done;
}
 
Example 14
Source File: NIOConnector.java    From ServletContainer with GNU General Public License v3.0 4 votes vote down vote up
public void accept(SelectionKey selectionKey) throws IOException {
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
    SocketChannel socketChannel = serverSocketChannel.accept();
    socketChannel.configureBlocking(false);
    socketChannel.register(this.selector,SelectionKey.OP_READ);
}
 
Example 15
Source File: LotsOfCancels.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 16
Source File: XulHttpServer.java    From starcor.xul with GNU Lesser General Public License v3.0 4 votes vote down vote up
void notifyWritable() throws IOException {
	if (_responseBuffer == null) {
		return;
	}

	final SocketChannel socketChannel = _socketChannel;
	socketChannel.write(_responseBuffer);
	if (!_responseBuffer.hasRemaining()) {
		if (_response.hasUserBodyStream()) {
			final Selector selector = _server._selector;
			final XulHttpServerHandler attachment = this;
			socketChannel.register(selector, 0, attachment);
			selector.wakeup();
			_server._reactorPool.execute(new Runnable() {
				@Override
				public void run() {
					try {
						int beginOffset = _sendChunkedData ? 32 : 0;
						int endOffset = _sendChunkedData ? 2 : 0;
						int sizeLimit = _sendChunkedData ? 8192 : -1;
						if (_response == null || !_response.prepareUserBodyData(beginOffset, endOffset, sizeLimit)) {
							terminate();
							return;
						}
						int dataSize = _response.getDataSize();
						if (dataSize <= 0) {
							if (_sendChunkedData) {
								_response.writeStream(null);
								_responseBuffer = ByteBuffer.wrap("0\r\n\r\n".getBytes());
							} else {
								terminate();
								return;
							}
						} else {
							final byte[] data = _response.getData();
							if (_sendChunkedData) {
								String dataLength = String.format("%X\r\n", dataSize);
								final byte[] dataLengthBytes = dataLength.getBytes();
								beginOffset -= dataLengthBytes.length;
								System.arraycopy(dataLengthBytes, 0, data, beginOffset, dataLengthBytes.length);
								dataSize += dataLengthBytes.length;
								data[beginOffset + dataSize++] = '\r';
								data[beginOffset + dataSize++] = '\n';
							}
							_responseBuffer = ByteBuffer.wrap(data, beginOffset, dataSize);
						}
						socketChannel.register(selector, SelectionKey.OP_WRITE, attachment);
						selector.wakeup();
					} catch (Exception e) {
						terminate();
						XulLog.e(TAG, e);
					}
				}
			});
		} else {
			socketChannel.close();
		}
		return;
	}
}
 
Example 17
Source File: NioAsyncLoadBalanceClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
private void establishConnection() throws IOException {
    SocketChannel socketChannel = null;

    try {
        final PeerChannel peerChannel;
        synchronized (this) {
            if (isConnectionEstablished()) {
                return;
            }

            selector = Selector.open();
            socketChannel = createChannel();
            socketChannel.configureBlocking(true);

            peerChannel = createPeerChannel(socketChannel, nodeIdentifier.toString());
            channel = peerChannel;
        }

        // Perform handshake outside of the synchronized block. We do this because if the server-side is not very responsive,
        // the handshake may take some time. We don't want to block any other threads from interacting with this Client in
        // the meantime, especially web threads that may be calling #register or #unregister.
        peerChannel.performHandshake();

        synchronized (this) {
            socketChannel.configureBlocking(false);
            selectionKey = socketChannel.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ);
        }
    } catch (Exception e) {
        logger.error("Unable to connect to {} for load balancing", nodeIdentifier, e);

        close();

        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (final Exception e1) {
                e.addSuppressed(e1);
            }
        }

        throw e;
    }
}
 
Example 18
Source File: ConnectionTableNIO.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private void register(Selector selector, SocketChannel channel) throws ClosedChannelException
{
   // register the channel but don't enable OP_WRITE until we have a write request.
   m_key = channel.register(selector, 0, this);
}
 
Example 19
Source File: LotsOfCancels.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 20
Source File: IoHandler.java    From LightComm4J with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * close some operations
 * 
 * @param channel
 * channel
 * @param opsToClose
 * opsToClose
 * @throws ClosedChannelException
 * ClosedChannelException
 */
private void closeOps(SocketChannel channel, int opsToClose) throws ClosedChannelException {
	ContextBean bean = this.context.getChanToContextBean().get(channel);
	int ops = bean.getOps();
	ops = (~opsToClose) & ops;
	bean.setOps(ops);
	channel.register(this.selector, ops);
}