private final void socketrun() {
   do {
     if (link.socketport != 0) {
       try {
         Socket socket =
             new Socket(InetAddress.getByName(getCodeBase().getHost()), link.socketport);
         socket.setSoTimeout(30000);
         socket.setTcpNoDelay(true);
         link.s = socket;
       } catch (Exception _ex) {
         link.s = null;
       }
       link.socketport = 0;
     }
     if (link.runme != null) {
       Thread thread = new Thread(link.runme);
       thread.setDaemon(true);
       thread.start();
       link.runme = null;
     }
     if (link.iplookup != null) {
       String s = "unknown";
       try {
         s = InetAddress.getByName(link.iplookup).getHostName();
       } catch (Exception _ex) {
       }
       link.host = s;
       link.iplookup = null;
     }
     try {
       Thread.sleep(100L);
     } catch (Exception _ex) {
     }
   } while (true);
 }
Example #2
0
  public void open(int serverId) {
    close();
    Server server = ServerManager.getInstance().getServer(serverId);
    if (server == null) {
      return;
    }
    try {
      socket = new Socket();
      ///
      socket.setKeepAlive(true);
      socket.setTcpNoDelay(true);
      // socket.setSoLinger(true, 0);
      ///
      socket.connect(new InetSocketAddress(server.getIp(), server.getPort()), 3000);
      socket.setTcpNoDelay(true);
      socket.setSoTimeout(4000);
      in = new DataInputX(new BufferedInputStream(socket.getInputStream()));
      out = new DataOutputX(new BufferedOutputStream(socket.getOutputStream()));

      // *************//
      out.writeInt(NetCafe.TCP_CLIENT);
      out.flush();
      // *************//
      if (server.isConnected() == false) {
        System.out.println("Success to connect " + server.getIp() + ":" + server.getPort());
        server.setConnected(true);
      }
    } catch (Throwable t) {
      t.printStackTrace();
      close();
      server.setConnected(false);
    }
  }
Example #3
0
  public void run() {
    ServerSocket server = null;
    try {
      server = new ServerSocket(link.getSerPort());
      System.out.println("System Online!");
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }
    try {
      Socket remoteSocket = server.accept();
      System.out.println("remoteSocket accpet!");
      Socket localSocket = server.accept();
      System.out.println("localSocket  accpet!");
      remoteSocket.setSoTimeout(0);
      localSocket.setSoTimeout(0);

      remoteSocket.setTcpNoDelay(true);
      localSocket.setTcpNoDelay(true);

      new TransferDown(remoteSocket, localSocket, "ToCZ");
      new TransferUp(remoteSocket, localSocket, "ToYonYou");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #4
0
 private void passTcpFileDescriptor(
     LocalSocket fdSocket,
     OutputStream outputStream,
     String socketId,
     String dstIp,
     int dstPort,
     int connectTimeout)
     throws Exception {
   Socket sock = new Socket();
   sock.setTcpNoDelay(true); // force file descriptor being created
   if (protect(sock)) {
     try {
       sock.connect(new InetSocketAddress(dstIp, dstPort), connectTimeout);
       ParcelFileDescriptor fd = ParcelFileDescriptor.fromSocket(sock);
       tcpSockets.put(socketId, sock);
       fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()});
       outputStream.write('*');
       outputStream.flush();
       fd.detachFd();
     } catch (ConnectException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } catch (SocketTimeoutException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } finally {
       outputStream.flush();
     }
   } else {
     LogUtils.e("protect tcp socket failed");
   }
 }
  /**
   * Method declaration
   *
   * @return
   */
  private Session init() {

    try {
      mSocket.setTcpNoDelay(true);

      mInput = new DataInputStream(new BufferedInputStream(mSocket.getInputStream()));
      mOutput = new DataOutputStream(new BufferedOutputStream(mSocket.getOutputStream()));
      user = mInput.readUTF();

      String password = mInput.readUTF();
      Session c;

      try {
        mServer.trace(mThread + ":trying to connect user " + user);

        return mServer.mDatabase.connect(user, password);
      } catch (SQLException e) {
        write(new Result(e.getMessage(), e.getErrorCode()).getBytes());
      }
    } catch (Exception e) {
      mServer.trace(mThread + ":couldn't connect " + user);
    }

    close();

    return null;
  }
Example #6
0
  void test() throws Exception {
    InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort);
    Proxy httpProxy = new Proxy(Proxy.Type.HTTP, proxyAddress);

    try (ServerSocket ss = new ServerSocket(0);
        Socket sock = new Socket(httpProxy)) {
      sock.setSoTimeout(SO_TIMEOUT);
      sock.setTcpNoDelay(false);

      InetSocketAddress externalAddress =
          new InetSocketAddress(InetAddress.getLocalHost(), ss.getLocalPort());

      out.println("Trying to connect to server socket on " + externalAddress);
      sock.connect(externalAddress);
      try (Socket externalSock = ss.accept()) {
        // perform some simple checks
        check(sock.isBound(), "Socket is not bound");
        check(sock.isConnected(), "Socket is not connected");
        check(!sock.isClosed(), "Socket should not be closed");
        check(sock.getSoTimeout() == SO_TIMEOUT, "Socket should have a previously set timeout");
        check(sock.getTcpNoDelay() == false, "NODELAY should be false");

        simpleDataExchange(sock, externalSock);
      }
    }
  }
Example #7
0
 /**
  * Establish a connection with the Leader found by findLeader. Retries 5 times before giving up.
  *
  * @param addr - the address of the Leader to connect to.
  * @throws IOException - if the socket connection fails on the 5th attempt
  * @throws ConnectException
  * @throws InterruptedException
  */
 protected void connectToLeader(InetSocketAddress addr)
     throws IOException, ConnectException, InterruptedException {
   sock = new Socket();
   sock.setSoTimeout(self.tickTime * self.initLimit);
   for (int tries = 0; tries < 5; tries++) {
     try {
       sock.connect(addr, self.tickTime * self.syncLimit);
       sock.setTcpNoDelay(nodelay);
       break;
     } catch (IOException e) {
       if (tries == 4) {
         LOG.error("Unexpected exception", e);
         throw e;
       } else {
         LOG.warn("Unexpected exception, tries=" + tries + ", connecting to " + addr, e);
         sock = new Socket();
         sock.setSoTimeout(self.tickTime * self.initLimit);
       }
     }
     Thread.sleep(1000);
   }
   leaderIs = M2mBinaryInputArchive.getArchive(new BufferedInputStream(sock.getInputStream()));
   bufferedOutput = new BufferedOutputStream(sock.getOutputStream());
   leaderOs = M2mBinaryOutputArchive.getArchive(bufferedOutput);
 }
  /**
   * 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);
    }
  }
Example #9
0
  /**
   * Configures the socket for use
   *
   * @param sock
   * @throws SocketException, IllegalArgumentException if setting the options on the socket failed.
   */
  protected void initialiseSocket(Socket sock) throws SocketException, IllegalArgumentException {
    if (socketOptions != null) {
      IntrospectionSupport.setProperties(socket, socketOptions);
    }

    try {
      sock.setReceiveBufferSize(socketBufferSize);
      sock.setSendBufferSize(socketBufferSize);
    } catch (SocketException se) {
      LOG.warn("Cannot set socket buffer size = " + socketBufferSize);
      LOG.debug("Cannot set socket buffer size. Reason: " + se, se);
    }
    sock.setSoTimeout(soTimeout);

    if (keepAlive != null) {
      sock.setKeepAlive(keepAlive.booleanValue());
    }

    if (soLinger > -1) {
      sock.setSoLinger(true, soLinger);
    } else if (soLinger == -1) {
      sock.setSoLinger(false, 0);
    }
    if (tcpNoDelay != null) {
      sock.setTcpNoDelay(tcpNoDelay.booleanValue());
    }
    if (!this.trafficClassSet) {
      this.trafficClassSet = setTrafficClass(sock);
    }
  }
Example #10
0
 SocketConnection(Socket socket, int buffersize) throws IOException {
   this.socket = socket;
   socket.setSoTimeout(30000);
   socket.setTcpNoDelay(true);
   inputstreamWorker = new InputstreamWorker(socket.getInputStream(), buffersize);
   outputstreamWorker = new OutputstreamWorker(socket.getOutputStream(), buffersize);
 }
Example #11
0
  /**
   * Listen for one object and place it on the request queue
   *
   * @throws IOException
   * @throws InterruptedException
   * @throws RadiusException
   */
  public void listen() throws Exception {
    RadiusLog.debug("Listening on socket...");
    Socket socket = serverSocket.accept();

    socket.setTcpNoDelay(false);

    if (keepAlive) {
      KeepAliveListener keepAliveListener = new KeepAliveListener(socket, this, queue);
      keepAliveListener.start();

      synchronized (keepAliveListeners) {
        keepAliveListeners.add(keepAliveListener);
      }
    } else {
      TCPListenerRequest lr = (TCPListenerRequest) requestObjectPool.borrowObject();
      lr.setBorrowedFromPool(requestObjectPool);
      lr.accept(socket, this, false, false);

      while (true) {
        try {
          this.queue.put(lr);
          break;
        } catch (InterruptedException e) {
        }
      }
    }
  }
Example #12
0
  /** Constructor declaration */
  public JICPConnection(TransportAddress ta, int timeout) throws IOException {
    // #MIDP_EXCLUDE_BEGIN
    // For some reason the local address or port may be in use
    while (true) {
      try {
        // #PJAVA_EXCLUDE_BEGIN
        sc = new Socket();
        bindSocket(sc);
        sc.setTcpNoDelay(true);
        sc.connect(new InetSocketAddress(ta.getHost(), Integer.parseInt(ta.getPort())), timeout);
        // #PJAVA_EXCLUDE_END
        /*#PJAVA_INCLUDE_BEGIN
        sc = new Socket(ta.getHost(), Integer.parseInt(ta.getPort()));
        #PJAVA_INCLUDE_END*/
        is = sc.getInputStream();
        os = getOutputStream();
        break;
      } catch (BindException be) {
        // Do nothing and try again
      }
    }
    // #MIDP_EXCLUDE_END

    /*#MIDP_INCLUDE_BEGIN
    String url = "socket://"+ta.getHost()+":"+ta.getPort();
    sc = (StreamConnection) Connector.open(url, Connector.READ_WRITE, false);
    is = sc.openInputStream();
    os = getOutputStream();
    #MIDP_INCLUDE_END*/
  }
  void applySocketParams(Socket s) {
    if (sendBuffer > 0) {
      try {
        s.setSendBufferSize(sendBuffer);
      } catch (SocketException e) {
        logger.error("error setting sendBuffer to " + sendBuffer, e);
      }
    }

    if (recvBuffer > 0) {
      try {
        s.setReceiveBufferSize(recvBuffer);
      } catch (SocketException e) {
        logger.error("error setting recvBuffer to " + recvBuffer, e);
      }
    }

    try {
      s.setTcpNoDelay(tcpNoDelay);
    } catch (SocketException e) {
      logger.error("error setting TcpNoDelay to " + tcpNoDelay, e);
    }

    try {
      s.setKeepAlive(keepAlive);
    } catch (SocketException e) {
      logger.error("error setting KeepAlive to " + keepAlive, e);
    }
  }
Example #14
0
 public static void startServer() {
   try {
     System.out.println("Starting server...");
     serverSocket = new ServerSocket(7788);
     System.out.println("Server Started... Address: " + serverSocket.getInetAddress());
     while (true) {
       socket = serverSocket.accept();
       for (int i = 0; i < 10; i++) {
         if (user[i] == null) {
           System.out.println("User " + (i + 1) + " connected from " + socket.getInetAddress());
           socket.setTcpNoDelay(false);
           out = new ObjectOutputStream(socket.getOutputStream());
           in = new ObjectInputStream(socket.getInputStream());
           out.writeInt(i);
           out.flush();
           User theUser = new User(out, in, i);
           user[i] = theUser;
           Thread thread = new Thread(user[i]);
           thread.start();
           break;
         }
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 private void connect() throws IOException {
   Socket tmp = null;
   try {
     tmp = socketFactory.createSocket();
     tmp.setTcpNoDelay(tcpNoDelay);
     if (sendBuffer > 0) tmp.setSendBufferSize(sendBuffer);
     tmp.bind(bindaddr);
     if (tmp instanceof SSLSocket) {
       SSLSocket sslsock = (SSLSocket) tmp;
       sslsock.setEnabledProtocols(new String[] {tlsProtocol});
       sslsock.setEnabledCipherSuites(tlsCiphers);
     }
     tmp.connect(addr, tcpConnectTimeout);
     if (tmp instanceof SSLSocket) {
       SSLSocket sslsock = (SSLSocket) tmp;
       sslsock.startHandshake();
     }
     sockout = new BufferedOutputStream(tmp.getOutputStream());
     sock = tmp;
     tmp = null;
   } finally {
     if (tmp != null)
       try {
         tmp.close();
       } catch (Exception ignore) {
       }
   }
 }
Example #16
0
  private void setSocketParameters(Socket client_sock) throws SocketException {
    if (log.isTraceEnabled())
      log.trace(
          "["
              + local_addr
              + "] accepted connection from "
              + client_sock.getInetAddress()
              + ":"
              + client_sock.getPort());
    try {
      client_sock.setSendBufferSize(send_buf_size);
    } catch (IllegalArgumentException ex) {
      if (log.isErrorEnabled())
        log.error("exception setting send buffer size to " + send_buf_size + " bytes", ex);
    }
    try {
      client_sock.setReceiveBufferSize(recv_buf_size);
    } catch (IllegalArgumentException ex) {
      if (log.isErrorEnabled())
        log.error("exception setting receive buffer size to " + send_buf_size + " bytes", ex);
    }

    client_sock.setKeepAlive(true);
    client_sock.setTcpNoDelay(tcp_nodelay);
    if (linger > 0) client_sock.setSoLinger(true, linger);
    else client_sock.setSoLinger(false, -1);
  }
  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 #18
0
    @Override
    public final void run() {
      try {
        final TcpPipe enclosing = TcpPipe.this;
        Log.log("startup send endpoint for %s @ ", enclosing, soport);

        Socket so = new Socket();
        so.setKeepAlive(true);
        so.setPerformancePreferences(SO_CONNTIME_PREF, SO_LATENCY_PREF, SO_BANDWIDTH_PREF);
        so.setTcpNoDelay(true);
        so.setSendBufferSize(SO_SND_BUFF_SIZE);

        Log.log("... connecting to port %d", soport);
        final InetAddress localhost = InetAddress.getLocalHost();
        SocketAddress endpoint = new InetSocketAddress(localhost, soport);

        so.connect(endpoint);
        Log.log("client connected to %s", so.getRemoteSocketAddress());

        if (!sndsocket_ref.compareAndSet(null, so))
          throw new IllegalStateException("sendInUpdater");

        Log.log("-- SND endpoint connected to remote endpoint %s", so.getRemoteSocketAddress());

      } catch (Exception e) {
        throw new RuntimeException("SND bootstrap failed", e);
      } finally {
        Log.log("SND endpoint established");
      }
    }
  void serviceClientApp(final Socket socket) throws Throwable {

    socket.setTcpNoDelay(true);

    final InputStream clientInput = socket.getInputStream();
    clientOutput = socket.getOutputStream();
    patchNumber = 1;

    mainFilePath = readPath(clientInput, false);

    byte ok[] = new byte[] {1, 0, 0, 0};
    clientOutput.write(ok);

    executablePath = readPath(clientInput, true);

    new Thread(
            new Runnable() {
              public void run() {
                try {
                  while (true) {
                    int bundleLoaded = readInt(clientInput);
                  }
                } catch (IOException e) {
                } finally {
                  try {
                    socket.close();
                  } catch (IOException e) {
                  }
                  clientOutput = null;
                }
              }
            })
        .start();
  }
 @Override
 public void setTcpNoDelay(boolean tcpNoDelay) {
   try {
     socket.setTcpNoDelay(tcpNoDelay);
   } catch (SocketException e) {
     throw new ChannelException(e);
   }
 }
 protected void initSocket(Socket socket) throws Exception {
   if (ioService.getSocketLingerSeconds() > 0) {
     socket.setSoLinger(true, ioService.getSocketLingerSeconds());
   }
   socket.setKeepAlive(ioService.getSocketKeepAlive());
   socket.setTcpNoDelay(ioService.getSocketNoDelay());
   socket.setReceiveBufferSize(ioService.getSocketReceiveBufferSize() * KILO_BYTE);
   socket.setSendBufferSize(ioService.getSocketSendBufferSize() * KILO_BYTE);
 }
Example #22
0
 @Override
 public void open() throws IOException {
   if (_socket != null) {
     _socket.close();
   }
   _socket = new java.net.Socket(this._host, this._port);
   // Disable Nagle's algorithm, preventing delays in sending bundles to the daemon
   _socket.setTcpNoDelay(true);
 }
Example #23
0
 /** @param on */
 public final void setTcpNoDelay(boolean on) {
   try {
     sock.setTcpNoDelay(on);
   } catch (SocketException e) {
     /*
      * Mantem o default em caso de excep��o.
      */
   }
 }
Example #24
0
  public TcpSocketPeer(Socket socket) {
    this.socket = socket;

    // turn off Nagle's algorithm since we should
    // always be doing buffering in the virtual machine
    try {
      socket.setTcpNoDelay(true);
    } catch (Exception e) {
    }
  }
Example #25
0
 /** 启动服务,监听端口用于接收联通上行信息 */
 public void startSvr() throws IOException {
   while (true) {
     Socket unicomSocket = null;
     unicomSocket = spsvrSocket.accept();
     unicomSocket.setSoLinger(true, 0); // socket关闭时,不再发送缓冲区里的数据,立即释放低层资源
     unicomSocket.setTcpNoDelay(true); // 不使用缓冲区,立即发送数据
     unicomSocket.setTrafficClass(0x04 | 0x10);
     exec.execute(new DealThread(unicomSocket));
   }
 }
Example #26
0
 /* ------------------------------------------------------------ */
 protected void configure(Socket socket) throws IOException {
   try {
     socket.setTcpNoDelay(true);
     if (_maxIdleTime >= 0) socket.setSoTimeout(_maxIdleTime);
     if (_soLingerTime >= 0) socket.setSoLinger(true, _soLingerTime / 1000);
     else socket.setSoLinger(false, 0);
   } catch (Exception e) {
     Log.ignore(e);
   }
 }
  public void setAcceptedSocketOptions(Acceptor acceptor, ServerSocket serverSocket, Socket socket)
      throws SocketException {

    if (_logger.isLoggable(Level.FINE)) {
      _logger.log(
          Level.FINE, "setAcceptedSocketOptions: " + acceptor + " " + serverSocket + " " + socket);
    }
    // Disable Nagle's algorithm (i.e., always send immediately).
    socket.setTcpNoDelay(true);
  }
Example #28
0
  /**
   * Open the Socket to the destination endpoint and
   *
   * @return the open java Socket.
   * @throws IOException
   */
  public Socket connect() throws IOException {
    LOG.info("Connecting to endpoint: " + endpoint);
    socket = new Socket();
    socket.setTcpNoDelay(true);
    socket.connect(endpoint, 1000);

    out = socket.getOutputStream();
    in = socket.getInputStream();

    return socket;
  }
Example #29
0
 /** Initializes the socket object */
 private void initSocket() {
   socket_ = new Socket();
   try {
     socket_.setSoLinger(false, 0);
     socket_.setTcpNoDelay(true);
     socket_.setKeepAlive(true);
     socket_.setSoTimeout(timeout_);
   } catch (SocketException sx) {
     LOGGER.error("Could not configure socket.", sx);
   }
 }
Example #30
0
  @Override
  public void run() {
    while (datanode.shouldRun) {
      Socket s = null;
      try {
        s = ss.accept();
        s.setTcpNoDelay(true);
        // Timeouts are set within DataXceiver.run()

        // Make sure the xceiver count is not exceeded
        int curXceiverCount = datanode.getXceiverCount();
        if (curXceiverCount > maxXceiverCount) {
          throw new IOException(
              "Xceiver count "
                  + curXceiverCount
                  + " exceeds the limit of concurrent xcievers: "
                  + maxXceiverCount);
        }

        new Daemon(datanode.threadGroup, DataXceiver.create(s, datanode, this)).start();
      } catch (SocketTimeoutException ignored) {
        // wake up to see if should continue to run
      } catch (AsynchronousCloseException ace) {
        // another thread closed our listener socket - that's expected during shutdown,
        // but not in other circumstances
        if (datanode.shouldRun) {
          LOG.warn(datanode.getDisplayName() + ":DataXceiverServer: ", ace);
        }
      } catch (IOException ie) {
        IOUtils.closeSocket(s);
        LOG.warn(datanode.getDisplayName() + ":DataXceiverServer: ", ie);
      } catch (OutOfMemoryError ie) {
        IOUtils.closeSocket(s);
        // DataNode can run out of memory if there is too many transfers.
        // Log the event, Sleep for 30 seconds, other transfers may complete by
        // then.
        LOG.warn("DataNode is out of memory. Will retry in 30 seconds.", ie);
        try {
          Thread.sleep(30 * 1000);
        } catch (InterruptedException e) {
          // ignore
        }
      } catch (Throwable te) {
        LOG.error(datanode.getDisplayName() + ":DataXceiverServer: Exiting due to: ", te);
        datanode.shouldRun = false;
      }
    }
    try {
      ss.close();
    } catch (IOException ie) {
      LOG.warn(datanode.getDisplayName() + " :DataXceiverServer: close exception", ie);
    }
  }