Пример #1
0
  private void accept(SelectionKey key) throws IOException {
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

    SocketChannel socketChannel = serverSocketChannel.accept();
    socketChannel.configureBlocking(false);
    socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
    socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    socketChannel.register(selector, SelectionKey.OP_READ);

    System.out.println("Client is connected");
  }
Пример #2
0
 /** Accept a connection, and close it immediately causing a hard reset. */
 static void acceptAndReset(ServerSocketChannel ssc) throws IOException {
   SocketChannel peer = ssc.accept();
   try {
     peer.setOption(StandardSocketOption.SO_LINGER, 0);
     peer.configureBlocking(false);
     peer.write(ByteBuffer.wrap(new byte[128 * 1024]));
   } finally {
     peer.close();
   }
 }
 @SuppressWarnings("unchecked")
 public Connection make(SocketChannel channel) throws IOException {
   channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
   // 子类完成具体连接创建工作
   Connection c = makeConnection(channel);
   // 设置连接的参数
   NetSystem.getInstance().setSocketParams(c, true);
   // 设置NIOHandler
   c.setHandler(getNIOHandler());
   return c;
 }
Пример #4
0
    public static ByteChannel create(String host, int port, Logger logger) throws IOException {
      SocketChannel channel = SocketChannel.open();
      channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
      channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
      channel.connect(new InetSocketAddress(host, port));

      if (logger.isTraceEnabled()) {
        return new LoggingByteChannel(new AllOrNothingChannel(channel), logger);
      } else {
        return new AllOrNothingChannel(channel);
      }
    }
Пример #5
0
  /**
   * Initialize the SocketStream with a new Socket.
   *
   * @param s the new socket.
   */
  public void init(SocketChannel s) {
    _s = s;

    try {
      s.setOption(StandardSocketOptions.TCP_NODELAY, true);
    } catch (Exception e) {
      e.printStackTrace();
      ;
    }
    // _is = null;
    // _os = null;
    _needsFlush = false;

    _readBuffer.clear().flip();
    _writeBuffer.clear();
  }
Пример #6
0
  @Override
  public void open() throws IOException {
    if (channel == null) {
      channel = SocketChannel.open();
      channel.configureBlocking(false);

      if (maxSendBufferSize > 0) {
        channel.setOption(StandardSocketOptions.SO_SNDBUF, maxSendBufferSize);
        final int actualSendBufSize = channel.getOption(StandardSocketOptions.SO_SNDBUF);
        if (actualSendBufSize < maxSendBufferSize) {
          logger.warn(
              "Attempted to set Socket Send Buffer Size to "
                  + maxSendBufferSize
                  + " bytes but could only set to "
                  + actualSendBufSize
                  + "bytes. You may want to "
                  + "consider changing the Operating System's maximum receive buffer");
        }
      }
    }

    if (!channel.isConnected()) {
      final long startTime = System.currentTimeMillis();
      final InetSocketAddress socketAddress =
          new InetSocketAddress(InetAddress.getByName(host), port);

      if (!channel.connect(socketAddress)) {
        while (!channel.finishConnect()) {
          if (System.currentTimeMillis() > startTime + timeout) {
            throw new SocketTimeoutException("Timed out connecting to " + host + ":" + port);
          }

          try {
            Thread.sleep(50L);
          } catch (final InterruptedException e) {
          }
        }
      }

      socketChannelOutput = new SocketChannelOutputStream(channel);
      socketChannelOutput.setTimeout(timeout);
    }
  }
  @Override
  public void run() {
    try {
      while (!mStopSignal) {
        final SocketChannel lSocketChannel = mServerSocketChannel.accept();
        // System.out.println("connection accepted");
        lSocketChannel.setOption(
            StandardSocketOptions.SO_SNDBUF, ClearVolumeTCPClient.cSocketBufferLength);

        try {
          if (lSocketChannel.isOpen()
              && lSocketChannel.isConnected()
              && mClearVolumeTCPServerSink.getLastVolumeSeen() != null) {
            // System.out.println("sending last seen volume: " +
            // mClearVolumeTCPServerSink.getLastVolumeSeen());
            sendVolumeToClient(
                lSocketChannel, mClearVolumeTCPServerSink.getLastVolumeSeen(), false);
          }

          while (lSocketChannel.isOpen() && lSocketChannel.isConnected() && !mStopSignal) {
            final Volume lVolumeToSend =
                mVolumeSource.requestVolumeAndWait(10, TimeUnit.MILLISECONDS);
            if (lVolumeToSend != null) sendVolumeToClient(lSocketChannel, lVolumeToSend, true);
          }
        } catch (final java.io.IOException e1) {
          continue;
        } catch (final Throwable e) {
          e.printStackTrace();
        }
      }

    } catch (final java.nio.channels.AsynchronousCloseException e) {
    } catch (final Throwable e) {
      handleError(e);
    } finally {
      mStoppedSignal = true;
    }
  }
Пример #8
0
 @Override
 public <T> SocketChannel setOption(SocketOption<T> name, T value) throws IOException {
   socketChannel = socketChannel.setOption(name, value);
   return this;
 }