Пример #1
0
  public StreamEngine(SocketChannel fd_, final Options options_, final String endpoint_) {
    handle = fd_;
    inbuf = null;
    insize = 0;
    io_enabled = false;
    outbuf = null;
    outsize = 0;
    handshaking = true;
    session = null;
    options = options_;
    plugged = false;
    terminating = false;
    endpoint = endpoint_;
    socket = null;
    greeting = ByteBuffer.allocate(GREETING_SIZE);
    greeting_output_buffer = ByteBuffer.allocate(GREETING_SIZE);
    encoder = null;
    decoder = null;

    //  Put the socket into non-blocking mode.
    try {
      Utils.unblock_socket(handle);

      //  Set the socket buffer limits for the underlying socket.
      if (options.sndbuf != 0) {
        handle.socket().setSendBufferSize((int) options.sndbuf);
      }
      if (options.rcvbuf != 0) {
        handle.socket().setReceiveBufferSize((int) options.rcvbuf);
      }

    } catch (IOException e) {
      throw new ZError.IOException(e);
    }
  }
Пример #2
0
  /** Check for new client connections */
  private void acceptNewConnections() {

    try {
      SocketChannel clientChannel;
      // since sSockChan is non-blocking, this will return immediately
      // regardless of whether there is a connection available
      while ((clientChannel = sSockChan.accept()) != null) {
        if (getContext().getServer().isRedirectActive()) {
          LOG.debug(
              "Client redirected to {}: {}",
              getContext().getServer().getRedirectAddress().getHostAddress(),
              clientChannel.socket().getInetAddress().getHostAddress());
          redirectAndKill(clientChannel.socket());
          continue;
        }

        Client client =
            getContext().getClients().addNewClient(clientChannel, readSelector, SEND_BUFFER_SIZE);
        if (client == null) {
          continue;
        }

        // from this point on, we know that client
        // has been successfully connected
        client.sendWelcomeMessage();

        LOG.debug("New client connected: {}", client.getIp().getHostAddress());
      }
    } catch (Exception ex) {
      LOG.error("Exception in acceptNewConnections(): " + ex.getMessage(), ex);
    }
  }
Пример #3
0
  /* ------------------------------------------------------------ */
  public void startConnection(HttpDestination destination) throws IOException {
    SocketChannel channel = null;
    try {
      channel = SocketChannel.open();
      Address address = destination.isProxied() ? destination.getProxy() : destination.getAddress();
      channel.socket().setTcpNoDelay(true);

      if (_httpClient.isConnectBlocking()) {
        channel.socket().connect(address.toSocketAddress(), _httpClient.getConnectTimeout());
        channel.configureBlocking(false);
        _selectorManager.register(channel, destination);
      } else {
        channel.configureBlocking(false);
        channel.connect(address.toSocketAddress());
        _selectorManager.register(channel, destination);
        ConnectTimeout connectTimeout = new ConnectTimeout(channel, destination);
        _httpClient.schedule(connectTimeout, _httpClient.getConnectTimeout());
        _connectingChannels.put(channel, connectTimeout);
      }
    } catch (UnresolvedAddressException ex) {
      if (channel != null) channel.close();
      destination.onConnectionFailed(ex);
    } catch (IOException ex) {
      if (channel != null) channel.close();
      destination.onConnectionFailed(ex);
    }
  }
Пример #4
0
  /**
   * Called when a new connection is pending on the underlying {@link ServerSocketChannel}.
   *
   * @param key The {@link SelectionKey} for the socket on which a connection is pending.
   * @throws IOException if an error occurs while accepting the new connection.
   */
  protected void accept(SelectionKey key) throws IOException {
    // Pull out the socket channel that has a connection pending
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

    // Accept the connection
    SocketChannel socketChannel = serverSocketChannel.accept();
    Socket socket = socketChannel.socket();

    // Check if our AcceptPolicy will allow this new connection
    if (this.acceptPolicy != null
        && !this.acceptPolicy.shouldRetain(socketChannel, this.getSocketSelector().keys().size())) {
      if (log.logTrace()) {
        log.trace("Closing accepted connection (accept policy enforced)");
      }
      socketChannel.close();
      return;
    }

    this.registerChannel(socketChannel);

    // Register the new socket. This will promote it to an SSLSocket
    // if we're configured for HTTPS.
    this.registerSocket(socket, this.host, this.port, false);

    // Add the new SocketChannel to our Selector
    socketChannel.configureBlocking(false);
    SelectionKey acceptKey = socketChannel.register(this.getSocketSelector(), SelectionKey.OP_READ);

    this.resetClientTimer(socketChannel.socket());
  }
 /**
  * @param selector The selector.
  * @param server The server socket channel.
  * @param now The current time.
  * @throws IOException Any IOException.
  */
 @Override
 protected void doAccept(final Selector selector, ServerSocketChannel server, long now)
     throws IOException {
   logger.debug("New accept");
   SocketChannel channel = server.accept();
   if (isShuttingDown()) {
     if (logger.isInfoEnabled()) {
       logger.info(
           "New connection from "
               + channel.socket().getInetAddress().getHostAddress()
               + " rejected; the server is in the process of shutting down.");
     }
     channel.close();
   } else {
     try {
       channel.configureBlocking(false);
       Socket socket = channel.socket();
       setSocketAttributes(socket);
       TcpNioConnection connection = createTcpNioConnection(channel);
       if (connection == null) {
         return;
       }
       connection.setTaskExecutor(getTaskExecutor());
       connection.setLastRead(now);
       this.channelMap.put(channel, connection);
       channel.register(selector, SelectionKey.OP_READ, connection);
       connection.publishConnectionOpenEvent();
     } catch (Exception e) {
       logger.error("Exception accepting new connection", e);
       channel.close();
     }
   }
 }
  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;
    }
  }
Пример #7
0
  /**
   * @throws IOException
   * @throws InterruptedException
   */
  protected synchronized void reConnect() throws IOException, InterruptedException {
    // 0. Don't send connect request if it is connecting.
    if (isNotConnected()) {
      SocketAddress remoteAddress = new InetSocketAddress(this.host, this.port);

      // 1. Create socket channel
      SocketChannel channel = SocketChannel.open();
      channel.configureBlocking(false);
      channel.socket().setTcpNoDelay(true);
      channel.socket().setReceiveBufferSize(48 * 1024);
      channel.socket().setSendBufferSize(48 * 1024);
      channel.connect(remoteAddress);

      // 2. Create NioSession for each client connection
      IoSession client =
          new DefaultIoSession().setChannel(channel).setIoWork(ioWorker).setEventWork(eventWorker);
      // 3. Register event
      reactorManager.nextReactor().registerSession(client, SelectionKey.OP_CONNECT);

      // 4. Wait to connect
      if (!client.waitToConnect(connectTimeout, TimeUnit.MILLISECONDS)) {
        client.close(); // TODO:asyncClose();
        throw new IOException("connect timed out to " + this.host + ":" + this.port);
      }

      IoSession.Status status = client.getStatus();
      if (status == IoSession.Status.NOT_CONNECT || status == IoSession.Status.CLOSED) {
        client.close(); // TODO:.asyncClose();
        throw new IOException("connect failed to " + this.host + ":" + this.port);
      }

      this.session = client;
    }
  }
Пример #8
0
  public static void main(String[] args) throws Exception {
    ServerSocketChannel ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0));
    try {
      InetAddress lh = InetAddress.getLocalHost();
      int port = ((InetSocketAddress) (ssc.getLocalAddress())).getPort();
      SocketAddress remote = new InetSocketAddress(lh, port);

      // Test SocketChannel shutdownXXX
      SocketChannel sc;
      sc = SocketChannel.open(remote);
      try {
        acceptAndReset(ssc);
        sc.shutdownInput();
        sc.shutdownOutput();
      } finally {
        sc.close();
      }

      // Test Socket adapter shutdownXXX and isShutdownInput
      sc = SocketChannel.open(remote);
      try {
        acceptAndReset(ssc);
        boolean before = sc.socket().isInputShutdown();
        sc.socket().shutdownInput();
        boolean after = sc.socket().isInputShutdown();
        if (before || !after) throw new RuntimeException("Before and after test failed");
        sc.socket().shutdownOutput();
      } finally {
        sc.close();
      }
    } finally {
      ssc.close();
    }
  }
 public String getRemoteAddressInfo() {
   if (socketChannel != null) {
     return socketChannel.socket().getInetAddress().getHostName()
         + ":"
         + socketChannel.socket().getPort();
   } else {
     return null;
   }
 }
  @Override
  protected void onSelected(SelectionKey key) throws IOException {
    if (!key.isAcceptable()) {
      super.onSelected(key);
    } else if (!isOverloaded()) {
      try {
        // Accept the new connection
        SocketChannel socketChannel = getHelper().getServerSocketChannel().accept();

        if (socketChannel != null) {
          socketChannel.configureBlocking(false);
          getHelper().configure(socketChannel.socket());

          int connectionsCount = getHelper().getConnections().size();

          if ((getHelper().getMaxTotalConnections() == -1)
              || (connectionsCount <= getHelper().getMaxTotalConnections())) {
            Connection<Server> connection =
                getHelper()
                    .checkout(
                        socketChannel,
                        this,
                        (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress());
            connection.open();
            getHelper().getConnections().add(connection);

            if (getHelper().getLogger().isLoggable(Level.FINE)) {
              getHelper()
                  .getLogger()
                  .fine(
                      "Connection from \""
                          + connection.getSocketAddress()
                          + "\" accepted. New count: "
                          + getHelper().getConnections().size());
            }
          } else {
            // Rejection connection
            socketChannel.close();
            getHelper()
                .getLogger()
                .info("Maximum number of concurrent connections reached. New connection rejected.");
          }
        }
      } catch (ClosedByInterruptException ex) {
        getHelper().getLogger().log(Level.FINE, "ServerSocket channel was closed by interrupt", ex);
        throw ex;
      } catch (AsynchronousCloseException ace) {
        getHelper().getLogger().log(Level.FINE, "The server socket was closed", ace);
      } catch (SocketException se) {
        getHelper().getLogger().log(Level.FINE, "The server socket was closed", se);
      } catch (IOException ex) {
        getHelper()
            .getLogger()
            .log(Level.WARNING, "Unexpected error while accepting new connection", ex);
      }
    }
  }
Пример #11
0
    /** blocks until connected */
    @Override
    SelectableChannel doConnect() throws IOException, InterruptedException {
      boolean success = false;
      final SocketChannel socketChannel = SocketChannel.open();
      try {
        socketChannel.configureBlocking(false);
        socketChannel.socket().setReuseAddress(true);
        socketChannel.socket().setSoLinger(false, 0);
        socketChannel.socket().setSoTimeout(0);
        socketChannel.socket().setTcpNoDelay(true);

        try {
          socketChannel.connect(details.address());
        } catch (UnresolvedAddressException e) {
          this.connectLater();
        }

        // Under experiment, the concoction was found to be more successful if we
        // paused before registering the OP_CONNECT
        Thread.sleep(10);

        // the registration has be be run on the same thread as the selector
        addPendingRegistration(
            new Runnable() {
              @Override
              public void run() {

                final Attached attached = new Attached();
                attached.connector = ClientConnector.this;

                try {
                  socketChannel.register(selector, OP_CONNECT, attached);
                } catch (ClosedChannelException e) {
                  if (socketChannel.isOpen()) LOG.error("", e);
                }
              }
            });

        selector.wakeup();
        success = true;
        return socketChannel;

      } finally {
        if (!success) {
          try {
            try {
              socketChannel.socket().close();
            } catch (Exception e) {
              LOG.error("", e);
            }
            socketChannel.close();
          } catch (IOException e) {
            LOG.error("", e);
          }
        }
      }
    }
 @Override
 public ClientConnection call() throws Exception {
   if (!live) {
     throw new HazelcastException("ConnectionManager is not active!!!");
   }
   SocketChannel socketChannel = null;
   try {
     socketChannel = SocketChannel.open();
     Socket socket = socketChannel.socket();
     socket.setKeepAlive(socketOptions.isKeepAlive());
     socket.setTcpNoDelay(socketOptions.isTcpNoDelay());
     socket.setReuseAddress(socketOptions.isReuseAddress());
     if (socketOptions.getLingerSeconds() > 0) {
       socket.setSoLinger(true, socketOptions.getLingerSeconds());
     }
     int bufferSize = socketOptions.getBufferSize() * KILO_BYTE;
     if (bufferSize < 0) {
       bufferSize = DEFAULT_BUFFER_SIZE_BYTE;
     }
     socket.setSendBufferSize(bufferSize);
     socket.setReceiveBufferSize(bufferSize);
     socketChannel.socket().connect(address.getInetSocketAddress(), connectionTimeout);
     SocketChannelWrapper socketChannelWrapper =
         socketChannelWrapperFactory.wrapSocketChannel(socketChannel, true);
     final ClientConnection clientConnection =
         new ClientConnection(
             ClientConnectionManagerImpl.this,
             inSelector,
             outSelector,
             connectionIdGen.incrementAndGet(),
             socketChannelWrapper,
             executionService,
             invocationService,
             client.getSerializationService());
     socketChannel.configureBlocking(true);
     if (socketInterceptor != null) {
       socketInterceptor.onConnect(socket);
     }
     authenticator.auth(clientConnection);
     socketChannel.configureBlocking(isBlock);
     socket.setSoTimeout(0);
     if (!isBlock) {
       clientConnection.getReadHandler().register();
     }
     return clientConnection;
   } catch (Exception e) {
     if (socketChannel != null) {
       socketChannel.close();
     }
     throw ExceptionUtil.rethrow(e);
   }
 }
Пример #13
0
 public NIOClientTCPSocket(InetSocketAddress localAddress, NIOClientSocketListener socketListener)
     throws IOException {
   _socketType = SocketType.Outgoing;
   _channel = SocketChannel.open();
   if (localAddress != null) {
     InetSocketAddress modifiedLocalAddress = new InetSocketAddress(localAddress.getAddress(), 0);
     // System.out.println("Binding To Local Address:" + modifiedLocalAddress.getAddress());
     // LOG.info(this + "Binding To Local Address:" + modifiedLocalAddress.getAddress());
     _channel.socket().bind(modifiedLocalAddress);
   }
   _localAddress = (InetSocketAddress) _channel.socket().getLocalSocketAddress();
   setClientSocketOptions(_channel);
   _listener = socketListener;
 }
Пример #14
0
    private synchronized SSLEngine newSslEngine(SocketChannel channel) throws IOException {
      SslContextFactory sslContextFactory = _httpClient.getSslContextFactory();
      SSLEngine sslEngine;
      if (channel != null) {
        String peerHost = channel.socket().getInetAddress().getHostAddress();
        int peerPort = channel.socket().getPort();
        sslEngine = sslContextFactory.newSslEngine(peerHost, peerPort);
      } else {
        sslEngine = sslContextFactory.newSslEngine();
      }
      sslEngine.setUseClientMode(true);
      sslEngine.beginHandshake();

      return sslEngine;
    }
Пример #15
0
  private InetSocketAddress doConnect() throws CanalClientException {
    try {
      channel = SocketChannel.open();
      channel.socket().setSoTimeout(soTimeout);
      channel.connect(address);
      Packet p = Packet.parseFrom(readNextPacket(channel));
      if (p.getVersion() != 1) {
        throw new CanalClientException("unsupported version at this client.");
      }

      if (p.getType() != PacketType.HANDSHAKE) {
        throw new CanalClientException("expect handshake but found other type.");
      }
      //
      Handshake handshake = Handshake.parseFrom(p.getBody());
      supportedCompressions.addAll(handshake.getSupportedCompressionsList());
      //
      ClientAuth ca =
          ClientAuth.newBuilder()
              .setUsername(username)
              .setNetReadTimeout(10000)
              .setNetWriteTimeout(10000)
              .build();
      writeWithHeader(
          channel,
          Packet.newBuilder()
              .setType(PacketType.CLIENTAUTHENTICATION)
              .setBody(ca.toByteString())
              .build()
              .toByteArray());
      //
      Packet ack = Packet.parseFrom(readNextPacket(channel));
      if (ack.getType() != PacketType.ACK) {
        throw new CanalClientException("unexpected packet type when ack is expected");
      }

      Ack ackBody = Ack.parseFrom(ack.getBody());
      if (ackBody.getErrorCode() > 0) {
        throw new CanalClientException(
            "something goes wrong when doing authentication: " + ackBody.getErrorMessage());
      }

      return new InetSocketAddress(
          channel.socket().getLocalAddress(), channel.socket().getLocalPort());
    } catch (IOException e) {
      throw new CanalClientException(e);
    }
  }
Пример #16
0
  /**
   * Reads incoming data from the client:
   *
   * <UL>
   *   <LI>Reads some bytes from the SocketChannel
   *   <LI>create a protocolTask, to process this data, possibly generating an answer
   *   <LI>Inserts the Task to the ThreadPool
   * </UL>
   *
   * @throws
   * @throws IOException in case of an IOException during reading
   */
  public void read() {
    // do not read if OLD.protocol has terminated. only write of pending data is
    // allowed
    if (_protocol.shouldClose()) {
      return;
    }

    SocketAddress address = _sChannel.socket().getRemoteSocketAddress();
    logger.info("Reading from " + address);

    ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
    int numBytesRead = 0;
    try {
      numBytesRead = _sChannel.read(buf);
    } catch (IOException e) {
      numBytesRead = -1;
    }
    // is the channel closed??
    if (numBytesRead == -1) {
      // No more bytes can be read from the channel
      logger.info("client on " + address + " has disconnected");
      closeConnection();
      // tell the OLD.protocol that the connection terminated.
      _protocol.connectionTerminated();
      return;
    }

    // add the buffer to the OLD.protocol task
    buf.flip();
    _task.addBytes(buf);
    // add the OLD.protocol task to the OLD.reactor
    _data.getExecutor().execute(_task);
  }
Пример #17
0
  /**
   * Start the server running - accepting connections, receiving messages. If the server is already
   * running, it will not be started again. This method is designed to be called in its own thread
   * and will not return until the server is stopped.
   *
   * @throws RuntimeException if the server fails
   */
  public void run() {
    // ensure that the server is not started twice
    if (!state.compareAndSet(State.STOPPED, State.RUNNING)) {
      started(true);
      return;
    }

    Selector selector = null;
    ServerSocketChannel server = null;
    try {
      selector = Selector.open();
      server = ServerSocketChannel.open();
      server.socket().bind(new InetSocketAddress(port));
      server.configureBlocking(false);
      server.register(selector, SelectionKey.OP_ACCEPT);
      started(false);
      while (state.get() == State.RUNNING) {
        selector.select(100); // check every 100ms whether the server has been requested to stop
        for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) {
          SelectionKey key = it.next();
          try {
            // remove key from the ready list
            it.remove();
            if (key.isConnectable()) {
              ((SocketChannel) key.channel()).finishConnect();
            }
            if (key.isAcceptable()) {
              // accept connection
              SocketChannel client = server.accept();
              client.configureBlocking(false);
              client.socket().setTcpNoDelay(true);
              // channel is registered for further events such as read or write
              SelectionKey acceptKey = client.register(selector, SelectionKey.OP_READ);
              connection(acceptKey);
            }
            if (key.isReadable()) {
              for (ByteBuffer message : readIncomingMessage(key)) {
                messageReceived(message, key);
              }
            }
          } catch (IOException ioe) {
            resetKey(key);
            disconnected(key);
          }
        }
      }
    } catch (Throwable e) {
      throw new RuntimeException("Server failure: " + e.getMessage());
    } finally {
      try {
        selector.close();
        server.socket().close();
        server.close();
        state.set(State.STOPPED);
        stopped();
      } catch (Exception e) {
        // do nothing - server failed
      }
    }
  }
Пример #18
0
  /**
   * Establish a connection with the server.
   *
   * @return true in case the connection got established. False if not.
   */
  @SuppressWarnings("nls")
  public boolean connect() {
    try {
      final Servers usedServer = IllaClient.getInstance().getUsedServer();

      final String serverAddress;
      final int serverPort;
      if (usedServer == Servers.customserver) {
        serverAddress = IllaClient.getCfg().getString("serverAddress");
        serverPort = IllaClient.getCfg().getInteger("serverPort");
      } else {
        serverAddress = usedServer.getServerHost();
        serverPort = usedServer.getServerPort();
      }

      final InetSocketAddress address = new InetSocketAddress(serverAddress, serverPort);
      socket = SelectorProvider.provider().openSocketChannel();
      socket.configureBlocking(true);
      socket.socket().setPerformancePreferences(0, 2, 1);

      if (!socket.connect(address)) {
        while (socket.isConnectionPending()) {
          socket.finishConnect();
          try {
            Thread.sleep(1);
          } catch (@Nonnull final InterruptedException e) {
            LOGGER.warn("Waiting time for connection finished got interrupted");
          }
        }
      }

      sender = new Sender(outputQueue, socket);
      sender.setUncaughtExceptionHandler(NetCommCrashHandler.getInstance());
      inputThread = new Receiver(inputQueue, socket);
      inputThread.setUncaughtExceptionHandler(NetCommCrashHandler.getInstance());
      messageHandler = new MessageExecutor(inputQueue);
      messageHandler.setUncaughtExceptionHandler(NetCommCrashHandler.getInstance());

      sender.start();
      inputThread.start();
      messageHandler.start();

      keepAliveTimer =
          new Timer(
              INITIAL_DELAY,
              KEEP_ALIVE_DELAY,
              new Runnable() {
                @Override
                public void run() {
                  World.getNet().sendCommand(keepAliveCmd);
                }
              });
      keepAliveTimer.setRepeats(true);
      keepAliveTimer.start();
    } catch (@Nonnull final IOException e) {
      LOGGER.fatal("Connection error");
      return false;
    }
    return true;
  }
Пример #19
0
 /**
  * attempts to send data to the client<br>
  * if all the data has been successfully sent, the ConnectionHandler will automatically switch to
  * read only mode, otherwise it'll stay in it's current mode (which is read / write).
  *
  * @throws IOException if the write operation fails
  * @throws ClosedChannelException if the channel have been closed while registering to the
  *     Selector
  */
 public synchronized void write() {
   if (_outData.size() == 0) {
     // if nothing left in the output string, go back to read mode
     switchToReadOnlyMode();
     return;
   }
   // if there is something to send
   ByteBuffer buf = _outData.remove(0);
   if (buf.remaining() != 0) {
     try {
       _sChannel.write(buf);
     } catch (IOException e) {
       // this should never happen.
       e.printStackTrace();
     }
     // check if the buffer contains more data
     if (buf.remaining() != 0) {
       _outData.add(0, buf);
     }
   }
   // check if the OLD.protocol indicated close.
   if (_protocol.shouldClose()) {
     switchToWriteOnlyMode();
     if (buf.remaining() == 0) {
       closeConnection();
       SocketAddress address = _sChannel.socket().getRemoteSocketAddress();
       logger.info("disconnecting client on " + address);
     }
   }
 }
Пример #20
0
  @Override
  public void release() {
    try {
      mcastObject(null, slaves.length);
      flushBuffers(0);
    } catch (Exception e) {
      log.warn("Failed to send termination to slaves.", e);
    }
    try {
      discoverySelector.close();
    } catch (Throwable e) {
      log.warn("Error closing discovery selector", e);
    }
    try {
      communicationSelector.close();
    } catch (Throwable e) {
      log.warn("Error closing comunication selector", e);
    }
    for (SocketChannel sc : slaves) {
      try {
        sc.socket().close();
      } catch (Throwable e) {
        log.warn("Error closing channel", e);
      }
    }

    try {
      if (serverSocketChannel != null) serverSocketChannel.socket().close();
    } catch (Throwable e) {
      log.warn("Error closing server socket channel", e);
    }
  }
Пример #21
0
 protected SelectableChannel getSelectableChannel(
     SocketAddress remoteAddress, SocketAddress localAddress) throws IOException {
   SocketChannel newSocketChannel = SocketChannel.open();
   Socket newSocket = newSocketChannel.socket();
   if (receiveBufferSize > 0) {
     try {
       newSocket.setReceiveBufferSize(receiveBufferSize);
     } catch (SocketException se) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setReceiveBufferSize exception ", se);
     } catch (IllegalArgumentException iae) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setReceiveBufferSize exception ", iae);
     }
   }
   if (sendBufferSize > 0) {
     try {
       newSocket.setSendBufferSize(sendBufferSize);
     } catch (SocketException se) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setSendBufferSize exception ", se);
     } catch (IllegalArgumentException iae) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setSendBufferSize exception ", iae);
     }
   }
   newSocket.setReuseAddress(reuseAddress);
   if (localAddress != null) newSocket.bind(localAddress);
   newSocketChannel.configureBlocking(false);
   return newSocketChannel;
 }
Пример #22
0
 Session newSession(final SocketChannel channel, Runnable writeCallback) {
   InetSocketAddress remoteSocketAddress =
       (InetSocketAddress) channel.socket().getRemoteSocketAddress();
   String remoteHostAddress =
       remoteSocketAddress.getAddress().getHostAddress() + ":" + remoteSocketAddress.getPort();
   return newSession(writeCallback, remoteHostAddress);
 }
 public static void main(String[] args) {
   try {
     SocketChannel socketChannel = SocketChannel.open();
     SocketAddress socketAddress = new InetSocketAddress("10.0.1.12", 10741);
     socketChannel.connect(socketAddress);
     OrderFactory o = new OrderFactory();
     Order order = o.SampleMessgeOrder();
     order.getOrderMessage().setOrderLevel("SystemLevelCommand");
     order.getOrderMessage().getOrderMethod().getMethod().get(0).setMethodName("systemStop");
     order
         .getOrderMessage()
         .getOrderMethod()
         .getMethod()
         .get(0)
         .getParameter()
         .get(0)
         .setParameter("4");
     order
         .getOrderMessage()
         .getOrderMethod()
         .getMethod()
         .get(0)
         .getParameter()
         .get(1)
         .setParameter("6");
     NIOServer.sendData(socketChannel, order);
     socketChannel.socket().shutdownOutput();
   } catch (Exception ex) {
     System.out.println("me: " + ex.getMessage());
   }
 }
Пример #24
0
 public void run() {
   try {
     while (!flag) {
       System.out.println("waiting connected.......");
       selector.select();
       Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
       while (keys.hasNext()) {
         SelectionKey key = keys.next();
         keys.remove();
         if (key.isAcceptable()) {
           ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
           SocketChannel sc = ssc.accept();
           sc.configureBlocking(false);
           SelectionKey clientKey = sc.register(selector, SelectionKey.OP_READ);
           System.out.println(sc.socket().getInetAddress().getHostAddress() + " 已连接");
         }
         if (key.isReadable()) {
           read(key);
         }
       }
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Пример #25
0
 protected void shutdownIO(final boolean read) {
   if (!isConnected()) {
     throw new NotYetConnectedException();
   }
   final SocketChannel channel = (SocketChannel) key.channel();
   try {
     final Method method =
         channel.getClass().getDeclaredMethod(read ? "shutdownInput" : "shutdownOutput");
     method.setAccessible(true);
     method.invoke(channel);
     return;
   } catch (NoSuchMethodException e) {
     logger.warn("{}", this, e);
   } catch (IllegalAccessException e) {
     logger.warn("{}", this, e);
   } catch (InvocationTargetException e) {
     logger.warn("{}", this, e);
   }
   final Socket socket = channel.socket();
   try {
     if (read) {
       socket.shutdownInput();
     } else {
       socket.shutdownOutput();
     }
   } catch (IOException e) {
     logger.warn("{}", this, e);
   }
 }
Пример #26
0
 boolean initiateConnection(Connection conn_, Peer peer) {
   TCPConnection conn = (TCPConnection) conn_;
   try {
     SocketChannel channel = SocketChannel.open();
     InetSocketAddress localAddress = new InetSocketAddress(conn.host_id, 0);
     channel.socket().bind(localAddress);
     channel.configureBlocking(false);
     try {
       InetSocketAddress remoteAddress = new InetSocketAddress(peer.host(), peer.port());
       if (channel.connect(remoteAddress)) {
         // This only happens on Solaris when connecting locally
         logger.log(Level.FINEST, "Connected!");
         conn.state = Connection.State.connected_out;
         conn.channel = channel;
         selector.wakeup();
         channel.register(selector, SelectionKey.OP_READ, conn);
         initiateCER(conn);
         return true;
       }
     } catch (java.nio.channels.UnresolvedAddressException ex) {
       channel.close();
       return false;
     }
     conn.state = Connection.State.connecting;
     conn.channel = channel;
     selector.wakeup();
     channel.register(selector, SelectionKey.OP_CONNECT, conn);
   } catch (java.io.IOException ex) {
     logger.log(
         Level.WARNING,
         "java.io.IOException caught while initiating connection to '" + peer.host() + "'.",
         ex);
   }
   return true;
 }
Пример #27
0
 private static void setClientSocketOptions(SocketChannel channel) throws IOException {
   channel.socket().setPerformancePreferences(0, 1, 3);
   channel.socket().setTcpNoDelay(true);
   probeAndSetSize(false, 2 << 16, 2 << 10, channel);
   probeAndSetSize(true, 2 << 15, 2 << 10, channel);
   channel.configureBlocking(false);
 }
Пример #28
0
  public static IRubyObject doAcceptNonblock(RubySocket sock, ThreadContext context, boolean ex) {
    try {
      Channel channel = sock.getChannel();
      if (channel instanceof SelectableChannel) {
        SelectableChannel selectable = (SelectableChannel) channel;

        synchronized (selectable.blockingLock()) {
          boolean oldBlocking = selectable.isBlocking();

          try {
            selectable.configureBlocking(false);

            IRubyObject socket = doAccept(sock, context, ex);
            if (!(socket instanceof RubySocket)) return socket;
            SocketChannel socketChannel = (SocketChannel) ((RubySocket) socket).getChannel();
            InetSocketAddress addr =
                (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress();

            return context.runtime.newArray(
                socket, Sockaddr.packSockaddrFromAddress(context, addr));
          } finally {
            selectable.configureBlocking(oldBlocking);
          }
        }
      } else {
        throw context.runtime.newErrnoENOPROTOOPTError();
      }
    } catch (IOException e) {
      throw sockerr(context.runtime, e.getLocalizedMessage(), e);
    }
  }
Пример #29
0
  // @Override
  public boolean finishConnect() throws IOException {
    if (_socketType == SocketType.Incoming) {
      throw new IOException("Invalid State-Connect called on an Incoming (server) Socket");
    }

    if (_channel == null) {
      throw new IOException("Invalid State - finishConnect called on closed channel");
    }

    try {
      if (_channel.finishConnect()) {

        _channel.socket().setKeepAlive(true);

        // LOG.info(this + "Connected to: " + _address.getAddress().getHostAddress() + ":" +
        // _address.getPort() + " via Interface:" +
        // _channel.socket().getLocalAddress().getHostAddress());

        return true;
      }
    } catch (IOException e) {
      // LOG.error("channel.finishConnect to address:" + _address.getAddress().getHostAddress() +"
      // port: " + _address.getPort() + " threw exception:" + e.toString());
      throw e;
    }
    return false;
  }
  /**
   * Create a client socket for the specified InetSocketAddress. Creates an SSL socket if the type
   * specified is SSL or SSL_MUTUALAUTH.
   *
   * @param type
   * @param inetSocketAddress
   * @return the socket.
   */
  public Socket createSocket(String type, InetSocketAddress inetSocketAddress) throws IOException {

    try {
      String host = inetSocketAddress.getHostName();
      int port = inetSocketAddress.getPort();
      if (_logger.isLoggable(Level.FINE)) {
        _logger.log(Level.FINE, "createSocket(" + type + ", " + host + ", " + port + ")");
      }
      if (type.equals(SSL) || type.equals(SSL_MUTUALAUTH)) {
        return createSSLSocket(host, port);
      } else {
        Socket socket = null;
        if (_logger.isLoggable(Level.FINE)) {
          _logger.log(Level.FINE, "Creating CLEAR_TEXT socket for:" + port);
        }

        if (orb.getORBData().connectionSocketType().equals(ORBConstants.SOCKETCHANNEL)) {
          SocketChannel socketChannel = ORBUtility.openSocketChannel(inetSocketAddress);
          socket = socketChannel.socket();
        } else {
          socket = new Socket(inetSocketAddress.getHostName(), inetSocketAddress.getPort());
        }

        // Disable Nagle's algorithm (i.e. always send immediately).
        socket.setTcpNoDelay(true);
        return socket;
      }
    } catch (Exception ex) {
      if (_logger.isLoggable(Level.FINE)) {
        _logger.log(Level.FINE, "Exception creating socket", ex);
      }
      throw new RuntimeException(ex);
    }
  }