private boolean _isOpenImpl() throws IOException {
   boolean wasBlocking = socketChannel.isBlocking();
   ByteBuffer buffer = ByteBuffer.allocate(1);
   if (wasBlocking) {
     socketChannel.configureBlocking(false);
   }
   int read;
   try {
     read = socketChannel.read(buffer);
   } catch (IOException e) {
     /* This should never happen in non Windows systems.
      * In Windows systems an IOException is thrown
      * whenever a client has closed its output connection
      * towards this channel and this method is called by
      * CommCore.
      */
     return false;
   }
   if (wasBlocking) {
     socketChannel.configureBlocking(true);
   }
   if (read == -1) {
     return false;
   } else if (read > 0) {
     istream.append(buffer.get(0));
   }
   return true;
 }
Exemple #2
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);
    }
  }
/* 350 */           while (((Iterator)localObject3).hasNext()) {
/* 351 */             SelectionKey localSelectionKey = (SelectionKey)((Iterator)localObject3).next();
/* 352 */             ((Iterator)localObject3).remove();
/* 353 */             if (localSelectionKey.equals(ServerImpl.this.listenerKey)) {
/* 354 */               if (!ServerImpl.this.terminating)
/*     */               {
/* 357 */                 SocketChannel localSocketChannel = ServerImpl.this.schan.accept();
/*     */ 
/* 360 */                 if (ServerConfig.noDelay()) {
/* 361 */                   localSocketChannel.socket().setTcpNoDelay(true);
/*     */                 }
/*     */ 
/* 364 */                 if (localSocketChannel != null)
/*     */                 {
/* 367 */                   localSocketChannel.configureBlocking(false);
/* 368 */                   localObject4 = localSocketChannel.register(ServerImpl.this.selector, 1);
/* 369 */                   localHttpConnection2 = new HttpConnection();
/* 370 */                   localHttpConnection2.selectionKey = ((SelectionKey)localObject4);
/* 371 */                   localHttpConnection2.setChannel(localSocketChannel);
/* 372 */                   ((SelectionKey)localObject4).attach(localHttpConnection2);
/* 373 */                   ServerImpl.this.requestStarted(localHttpConnection2);
/* 374 */                   ServerImpl.this.allConnections.add(localHttpConnection2);
/*     */                 }
/*     */               }
/*     */             }
/*     */             else {
/*     */               try
/*     */               {
/*     */                 Object localObject4;
/*     */                 HttpConnection localHttpConnection2;
/* 377 */                 if (localSelectionKey.isReadable())
/*     */                 {
/* 379 */                   localObject4 = (SocketChannel)localSelectionKey.channel();
/* 380 */                   localHttpConnection2 = (HttpConnection)localSelectionKey.attachment();
/*     */ 
/* 382 */                   localSelectionKey.cancel();
/* 383 */                   ((SocketChannel)localObject4).configureBlocking(true);
/* 384 */                   if (ServerImpl.this.idleConnections.remove(localHttpConnection2))
/*     */                   {
/* 387 */                     ServerImpl.this.requestStarted(localHttpConnection2);
/*     */                   }
/* 389 */                   handle((SocketChannel)localObject4, localHttpConnection2);
/*     */                 }
/* 391 */                 else if (!$assertionsDisabled) { throw new AssertionError(); }
/*     */               }
/*     */               catch (CancelledKeyException localCancelledKeyException) {
/* 394 */                 handleException(localSelectionKey, null);
/*     */               } catch (IOException localIOException2) {
/* 396 */                 handleException(localSelectionKey, localIOException2);
/*     */               }
/*     */             }
/*     */           }
 @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);
   }
 }
Exemple #5
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;
    }
  }
  /**
   * 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
      }
    }
  }
 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;
 }
Exemple #8
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());
  }
 private void attemptReconnects() throws IOException {
   final long now = System.currentTimeMillis();
   final Map<MemcachedNode, Boolean> seen = new IdentityHashMap<MemcachedNode, Boolean>();
   for (Iterator<MemcachedNode> i = reconnectQueue.headMap(now).values().iterator();
       i.hasNext(); ) {
     final MemcachedNode qa = i.next();
     i.remove();
     if (!seen.containsKey(qa)) {
       seen.put(qa, Boolean.TRUE);
       getLogger().info("Reconnecting %s", qa);
       final SocketChannel ch = SocketChannel.open();
       ch.configureBlocking(false);
       int ops = 0;
       if (ch.connect(qa.getSocketAddress())) {
         getLogger().info("Immediately reconnected to %s", qa);
         assert ch.isConnected();
       } else {
         ops = SelectionKey.OP_CONNECT;
       }
       qa.registerChannel(ch, ch.register(selector, ops, qa));
       assert qa.getChannel() == ch : "Channel was lost.";
     } else {
       getLogger().debug("Skipping duplicate reconnect request for %s", qa);
     }
   }
 }
 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);
 }
 private void connectSender() throws IOException {
   sender = SocketChannel.open();
   sender.configureBlocking(true);
   sender.socket().setTcpNoDelay(true);
   senderThread = new SenderThread();
   senderThread.start();
 }
Exemple #12
0
    void add(Target t) {
      SocketChannel sc = null;
      try {

        sc = SocketChannel.open();
        sc.configureBlocking(false);

        boolean connected = sc.connect(t.address);

        t.channel = sc;
        t.connectStart = System.currentTimeMillis();

        if (connected) {
          t.connectFinish = t.connectStart;
          sc.close();
          printer.add(t);
        } else {
          synchronized (pending) {
            pending.add(t);
          }

          sel.wakeup();
        }
      } catch (IOException x) {
        if (sc != null) {
          try {
            sc.close();
          } catch (IOException xx) {
          }
        }
        t.failure = x;
        printer.add(t);
      }
    }
  private void accept(SelectionKey key) throws IOException {
    // For an accept to be pending the channel must be a server socket channel.
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

    int tunnelId = createTunnel();
    logger.fine(
        "New incoming connection to device port "
            + serverSocketChannel.socket().getLocalPort()
            + "; tunnel "
            + tunnelId);

    try {
      // Accept the connection and make it non-blocking
      SocketChannel socketChannel = serverSocketChannel.accept();
      socketChannel.configureBlocking(false);

      registerRightChannel(tunnelId, socketChannel);
    } catch (IOException e) {
      logger.log(Level.SEVERE, "PROTOCOL ERROR: " + e.getMessage(), e);
      closeTunnel(tunnelId);
    }

    commandWriteBuffer.put(CMD_OPEN_CHANNEL);
    commandWriteBuffer.putInt(serverSocketChannel.socket().getLocalPort());
    commandWriteBuffer.putInt(tunnelId);
    writeCommand();
  }
  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;
    }
  }
Exemple #15
0
 /**
  * ���һ��Socketͨ�������Ը�ͨ����һЩ��ʼ���Ĺ���
  *
  * @param ip ���ӵķ�������ip
  * @param port ���ӵķ������Ķ˿ں�
  * @throws IOException
  */
 public void initClient(String ip, int port) {
   // ���һ��Socketͨ��
   SocketChannel channel = null;
   try {
     channel = SocketChannel.open();
     // ����ͨ��Ϊ������
     channel.configureBlocking(false);
     // ���һ��ͨ��������
     this.selector = Selector.open();
     // �ͻ������ӷ�����,��ʵ����ִ�в�û��ʵ�����ӣ���Ҫ��listen���������е�
     // ��channel.finishConnect();�����������
     channel.connect(new InetSocketAddress(ip, port));
     // ��ͨ���������͸�ͨ���󶨣���Ϊ��ͨ��ע��SelectionKey.OP_CONNECT�¼���
     channel.register(selector, SelectionKey.OP_CONNECT);
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     if (channel != null) {
       try {
         channel.close();
       } catch (IOException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
       }
     }
   }
 }
  private void listen() throws IOException {
    while (true) {
      int selec = selector.select(500);

      if (selec == 0) {
        continue;
      }

      Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
      while (iterator.hasNext()) {
        SelectionKey selectionKey = iterator.next();
        try {
          iterator.remove();

          if (selectionKey.isAcceptable()) {
            ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
            SocketChannel sc = ssc.accept();
            sc.configureBlocking(false);

            sc.register(selector, SelectionKey.OP_READ);
          } else if (selectionKey.isReadable()) {
            read(selectionKey);
          } else if (selectionKey.isWritable()) {
            write(selectionKey);
          }
        } catch (Exception e) {
          // iterator.remove(); Don't use it! It can throw a exception!
          SocketChannel sc = (SocketChannel) selectionKey.channel();
          sc.close();
        }
      }
    }
  }
  /**
   * Starts a new Thread and connects to server
   *
   * @throws IOException
   */
  public Thread connect() throws IOException {
    this.running = true;
    this.readyState = WEBSOCKET_STATE_CONNECTING;
    // open socket
    socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    // set address
    socketChannel.connect(new InetSocketAddress(uri.getHost(), port));
    // start a thread to make connection

    // More info:
    // http://groups.google.com/group/android-developers/browse_thread/thread/45a8b53e9bf60d82
    // http://stackoverflow.com/questions/2879455/android-2-2-and-bad-address-family-on-socket-connect
    System.setProperty("java.net.preferIPv4Stack", "true");
    System.setProperty("java.net.preferIPv6Addresses", "false");

    selector = Selector.open();
    socketChannel.register(selector, SelectionKey.OP_CONNECT);
    Log.v("websocket", "Starting a new thread to manage data reading/writing");

    Thread th = new Thread(this);
    th.start();
    // return thread object for explicit closing, if needed
    return th;
  }
 /**
  * @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();
     }
   }
 }
Exemple #19
0
 private void reconnect() {
   FVLog.log(LogLevel.INFO, this, "trying to reconnect to ", this.hostname, ":", this.port);
   // reset our state to unconnected (might be a NOOP)
   this.isConnected = false;
   this.msgStream = null;
   // try to connect socket to controller
   try {
     if (this.sock != null)
       // note that this automatically unregisters from selector
       this.sock.close();
     this.sock = SocketChannel.open();
     sock.configureBlocking(false); // set to non-blocking
     InetSocketAddress addr = new InetSocketAddress(hostname, port);
     if (addr.isUnresolved()) {
       FVLog.log(LogLevel.INFO, this, "retrying: failed to resolve hostname: ", hostname);
       this.reconnectLater();
       return;
     }
     this.isConnected = this.sock.connect(addr); // try to connect
     // register into event loop
     this.loop.register(this.sock, SelectionKey.OP_CONNECT, this);
   } catch (IOException e) {
     FVLog.log(LogLevel.CRIT, this, "Trying to reconnect; trying later; got : ", e);
     this.reconnectLater();
   }
 }
Exemple #20
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;
  }
  public void actionHandler(SelectionKey key) throws IOException {
    if (key.isAcceptable()) {
      ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
      SocketChannel socketChannel = serverChannel.accept();
      socketChannel.configureBlocking(false);
      socketChannel.register(roller, SelectionKey.OP_READ);
    } else if (key.isReadable()) {
      ByteBuffer buffer = ByteBuffer.allocate(16);
      SocketChannel socketChannel = (SocketChannel) key.channel();
      socketChannel.read(buffer);
      buffer.flip();
      String temp = decode(buffer);
      StringBuffer strBuffer = stringLocal.get();
      if (strBuffer == null) {
        strBuffer = new StringBuffer();
      }

      strBuffer.append(temp);

      if (temp.equals("\r\n")) {
        System.out.println(strBuffer.toString());
        strBuffer = null;
      }
      stringLocal.set(strBuffer);
    }
  }
  public void addTarget(Target target) {
    // 向targets队列中加入一个任务
    SocketChannel socketChannel = null;
    try {
      socketChannel = SocketChannel.open();
      socketChannel.configureBlocking(false);
      socketChannel.connect(target.address);

      target.channel = socketChannel;
      target.connectStart = System.currentTimeMillis();

      synchronized (targets) {
        targets.add(target);
      }
      selector.wakeup();
    } catch (Exception x) {
      if (socketChannel != null) {
        try {
          socketChannel.close();
        } catch (IOException xx) {
        }
      }
      target.failure = x;
      addFinishedTarget(target);
    }
  }
 /**
  * Construct a memcached connection.
  *
  * @param bufSize the size of the buffer used for reading from the server
  * @param f the factory that will provide an operation queue
  * @param a the addresses of the servers to connect to
  * @throws IOException if a connection attempt fails early
  */
 public MemcachedConnection(int bufSize, ConnectionFactory f, List<InetSocketAddress> a)
     throws IOException {
   reconnectQueue = new TreeMap<Long, MemcachedNode>();
   addedQueue = new ConcurrentLinkedQueue<MemcachedNode>();
   selector = Selector.open();
   List<MemcachedNode> connections = new ArrayList<MemcachedNode>(a.size());
   for (SocketAddress sa : a) {
     SocketChannel ch = SocketChannel.open();
     ch.configureBlocking(false);
     MemcachedNode qa = f.createMemcachedNode(sa, ch, bufSize);
     int ops = 0;
     if (ch.connect(sa)) {
       getLogger().info("Connected to %s immediately", qa);
       qa.connected();
       assert ch.isConnected();
     } else {
       getLogger().info("Added %s to connect queue", qa);
       ops = SelectionKey.OP_CONNECT;
     }
     qa.setSk(ch.register(selector, ops, qa));
     assert ch.isConnected() || qa.getSk().interestOps() == SelectionKey.OP_CONNECT
         : "Not connected, and not wanting to connect";
     connections.add(qa);
   }
   locator = f.createLocator(connections);
 }
Exemple #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();
   }
 }
  private void handle(SelectionKey key) throws IOException {
    // TODO Auto-generated method stub

    ServerSocketChannel server = null;
    SocketChannel client = null;
    String receiveText = null;
    int count = 0;

    if (key.isAcceptable()) {
      // client require accept events
      server = (ServerSocketChannel) key.channel();
      client = server.accept();
      client.configureBlocking(false);
      client.register(selector, SelectionKey.OP_READ);
    } else if (key.isReadable()) {
      // 如果是read事件,则直接读取
      client = (SocketChannel) key.channel();
      recBuffer.clear();
      count = client.read(recBuffer);
      if (count > 0) {
        recBuffer.flip();
        receiveText = decode.decode(recBuffer.asReadOnlyBuffer()).toString();
        System.out.println(client.toString() + ":" + receiveText);
        sendBuffer.clear();
        sendBuffer.put((sdf.format(new Date()) + "服务器收到你的消息").getBytes());
        sendBuffer.flip();
        client.write(sendBuffer);
        dispatch(client, receiveText);
        client = (SocketChannel) key.channel();
        client.register(selector, SelectionKey.OP_READ);
      }
    }
  }
Exemple #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;
 }
Exemple #27
0
 public SocketChannel getClientChannel(final boolean noTearDown) throws IOException {
   final List<String> listeners = m_config.getListenerAddresses();
   final Random r = new Random();
   final String listener = listeners.get(r.nextInt(listeners.size()));
   byte[] hashedPassword = ConnectionUtil.getHashedPassword(m_password);
   HostAndPort hNp = HostAndPort.fromString(listener);
   int port = Constants.DEFAULT_PORT;
   if (hNp.hasPort()) {
     port = hNp.getPort();
   }
   final SocketChannel channel =
       (SocketChannel)
           ConnectionUtil.getAuthenticatedConnection(
               hNp.getHostText(),
               m_username,
               hashedPassword,
               port,
               null,
               ClientAuthHashScheme.getByUnencodedLength(hashedPassword.length))[0];
   channel.configureBlocking(true);
   if (!noTearDown) {
     synchronized (m_clientChannels) {
       m_clientChannels.add(channel);
     }
   }
   return channel;
 }
  @Override
  public Void call() throws Exception {
    ServerSocketChannel clientConnection = (ServerSocketChannel) selectionKey.channel();
    SocketChannel channel = clientConnection.accept();

    if (channel != null) {
      channel.configureBlocking(false);

      LOGGER.info(
          String.format("%s accepted client connection from %s", name, channel.getRemoteAddress()));

      try {
        final HttpRequest.HttpRequestWrapper requestWrapper = requestParser.parse(read(channel));

        MethodHandler handler =
            RequestHandlerFactory.newInstance(requestWrapper.getRequestLine().getMethod());
        HttpResponse.HttpResponseWrapper responseWrapper = handler.handle(requestWrapper);
        write(channel, responseWrapper);
      } finally {
        channel.close();
      }

      LOGGER.info(String.format("%s is done.", name));
    }

    return null;
  }
 public void handleAccept(SelectionKey key) throws IOException {
   ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
   SocketChannel socketChannel = serverSocketChannel.accept();
   log.info("Server: accept client socket " + socketChannel);
   socketChannel.configureBlocking(false);
   socketChannel.register(key.selector(), SelectionKey.OP_READ);
 }
 public static void main(String[] args) throws IOException, InterruptedException {
   String nic = args.length > 0 ? args[0] : "0.0.0.0";
   int port = args.length > 1 ? Integer.parseInt(args[1]) : 12345;
   System.out.println("Listening on interface : " + nic + ":" + port);
   final ByteBuffer buffy = ByteBuffer.allocateDirect(PAGE_SIZE).order(ByteOrder.nativeOrder());
   final ServerSocketChannel serverSocket = ServerSocketChannel.open();
   serverSocket.socket().bind(new InetSocketAddress(nic, port));
   SocketChannel accepted = null;
   try {
     accepted = serverSocket.accept();
     accepted.socket().setTcpNoDelay(true);
     accepted.configureBlocking(false);
     serverSocket.close();
     Selector selector = Selector.open();
     accepted.register(selector, SelectionKey.OP_READ);
     while (!Thread.interrupted()) {
       if (pong(buffy, accepted, selector)) return;
     }
   } finally {
     if (accepted != null) {
       try {
         accepted.close();
       } catch (IOException ignored) {
       }
     }
   }
 }