예제 #1
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);
    }
  }
예제 #2
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");
      }
    }
예제 #3
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);
  }
예제 #4
0
 protected void connect() {
   try {
     Log.e(this.TAG, "connect() to " + this.host + ":" + this.port);
     SocketAddress sockaddr = new InetSocketAddress(this.host, this.port);
     Socket sock = new Socket();
     int timeout = 5 * 1000;
     sock.connect(sockaddr, timeout);
     sock.setKeepAlive(true);
     this.client = new AndroidXpraClient(this, sock.getInputStream(), sock.getOutputStream());
     this.client.setPassword(this.password);
     this.client.setOnExit(
         new Runnable() {
           @Override
           public void run() {
             XpraActivity.this.handler.post(
                 new Runnable() {
                   @Override
                   public void run() {
                     toast("Xpra client disconnected");
                     finish();
                   }
                 });
           }
         });
     new Thread(this.client).start();
   } catch (IOException e) {
     Log.e(this.TAG, "connect()", e);
     this.finish();
   }
 }
예제 #5
0
 private Socket newSocket() throws SocketException, IOException {
   Socket socket = new Socket();
   socket.setKeepAlive(keepAlive);
   socket.setSoTimeout(100);
   socket.connect(new InetSocketAddress(host, port), connectTimeout);
   return socket;
 }
예제 #6
0
 protected Socket makeSocket(String address, int port) throws UnknownHostException, IOException {
   Socket s;
   InetAddress addr = InetAddress.getByName(address);
   s = new Socket(addr, port);
   s.setKeepAlive(true);
   return s;
 }
예제 #7
0
  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);
    }
  }
예제 #8
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);
    }
  }
예제 #9
0
  private synchronized Socket getOrCreateSocket(boolean resend) throws NetworkIOException {
    if (reconnectPolicy.shouldReconnect()) {
      logger.debug("Reconnecting due to reconnectPolicy dictating it");
      UILogger.getInstance().add("Reconnecting due to reconnectPolicy dictating it");
      Utilities.close(socket);
      socket = null;
    }

    if (socket == null || socket.isClosed()) {
      try {
        if (proxy == null) {
          socket = factory.createSocket(host, port);
          logger.debug("Connected new socket {}", socket);
          UILogger.getInstance().add("Connected new socket" + socket.toString());
        } else if (proxy.type() == Proxy.Type.HTTP) {
          TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder();
          socket =
              tunnelBuilder.build(
                  (SSLSocketFactory) factory, proxy, proxyUsername, proxyPassword, host, port);
          logger.debug("Connected new socket through http tunnel {}", socket);
          UILogger.getInstance()
              .add("Connected new socket through http tunnel " + socket.toString());
        } else {
          boolean success = false;
          Socket proxySocket = null;
          try {
            proxySocket = new Socket(proxy);
            proxySocket.connect(new InetSocketAddress(host, port), connectTimeout);
            socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false);
            success = true;
          } finally {
            if (!success) {
              Utilities.close(proxySocket);
            }
          }
          logger.debug("Connected new socket through socks tunnel {}", socket);
          UILogger.getInstance()
              .add("Connected new socket through socks tunnel " + socket.toString());
        }

        socket.setSoTimeout(readTimeout);
        socket.setKeepAlive(true);

        if (errorDetection) {
          monitorSocket(socket);
        }

        reconnectPolicy.reconnected();
        logger.debug("Made a new connection to APNS");
        UILogger.getInstance().add("Made a new connection to APNS");
      } catch (IOException e) {
        logger.error("Couldn't connect to APNS server", e);
        UILogger.getInstance().add("Couldn't connect to APNS server" + e.toString());
        // indicate to clients whether this is a resend or initial send
        throw new NetworkIOException(e, resend);
      }
    }
    return socket;
  }
예제 #10
0
파일: Connection.java 프로젝트: alfr/jedis
 public void rollbackTimeout() {
   try {
     socket.setSoTimeout(timeout);
     socket.setKeepAlive(false);
   } catch (SocketException ex) {
     throw new JedisException(ex);
   }
 }
예제 #11
0
 @Override
 public void setKeepAlive(boolean keepAlive) {
   try {
     socket.setKeepAlive(keepAlive);
   } 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);
 }
예제 #13
0
파일: TSocket.java 프로젝트: yakolla/thrift
 /** 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);
   }
 }
예제 #14
0
 /**
  * set up tcp connection for socket
  *
  * @param ip the ip to connect
  * @param port the port to connect
  */
 private void setupTCPConnection(String ip, int port) {
   try {
     /* set up connection */
     cSocket = new Socket(ip, port);
     cSocket.setKeepAlive(true);
   } catch (UnknownHostException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
예제 #15
0
파일: Connection.java 프로젝트: alfr/jedis
 public void setTimeoutInfinite() {
   try {
     if (!isConnected()) {
       connect();
     }
     socket.setKeepAlive(true);
     socket.setSoTimeout(0);
   } catch (SocketException ex) {
     throw new JedisException(ex);
   }
 }
예제 #16
0
 public void initSocket() {
   socket = new Socket();
   try {
     socket.setSendBufferSize(Config.SOCKET_MAX_SEND_BUFFER_SIZE);
     socket.setReceiveBufferSize(Config.SOCKET_MAX_RECEIVE_BUFFER_SIZE);
     socket.setKeepAlive(Config.SOCKET_KEEP_ALIVE_ENABLED);
     socket.setTcpNoDelay(Config.SOCKET_TCP_NO_DELAY);
     socket.setReuseAddress(true);
   } catch (SocketException e) {
     Logger.printException(this, 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);
   }
 }
예제 #18
0
  /** {@inheritDoc} */
  @Override
  public AsyncSocketChannelImpl setOption(SocketOption name, Object value) throws IOException {
    if (!(name instanceof StandardSocketOption)) {
      throw new IllegalArgumentException("Unsupported option " + name);
    }

    if (value == null || !name.type().isAssignableFrom(value.getClass())) {
      throw new IllegalArgumentException("Bad parameter for " + name);
    }

    StandardSocketOption stdOpt = (StandardSocketOption) name;
    final Socket socket = channel.socket();

    try {
      switch (stdOpt) {
        case SO_TIMEOUT:
          // Timeout is not supported by SocketChannel, so we need to
          // implement it outside.
          socketTimeout = ((Integer) value).intValue();
          break;

        case SO_SNDBUF:
          socket.setSendBufferSize(((Integer) value).intValue());
          break;

        case SO_RCVBUF:
          socket.setReceiveBufferSize(((Integer) value).intValue());
          break;

        case SO_KEEPALIVE:
          socket.setKeepAlive(((Boolean) value).booleanValue());
          break;

        case SO_REUSEADDR:
          socket.setReuseAddress(((Boolean) value).booleanValue());
          break;

        case TCP_NODELAY:
          socket.setTcpNoDelay(((Boolean) value).booleanValue());
          break;

        default:
          throw new IllegalArgumentException("Unsupported option " + name);
      }
    } catch (SocketException e) {
      if (socket.isClosed()) {
        throw Util.initCause(new ClosedChannelException(), e);
      }
      throw e;
    }
    return this;
  }
예제 #19
0
    /**
     * Template method that sets up the socket right after the connection has been established.
     * Subclass implementations may implement their own logic by overriding doSetup
     */
    protected final void setup(Socket socket) throws IOException {
      socket.setSoTimeout(serverTimeout);
      socket.setKeepAlive(keepAlive);
      socket.setTcpNoDelay(true);

      try {
        SSLListenerUtil.addListener(orb, socket);
      } catch (Throwable t) {
        logger.warn("unexpected exception in ssl listener", t);
      }

      doSetup(socket);
    }
예제 #20
0
    @Override
    public void run() {

      Socket client = null;
      try {
        client = new Socket(ip, port);
        client.setKeepAlive(true);
      } catch (IOException e) {
        e.printStackTrace();
      }
      Timer t = new Timer();
      t.schedule(new sendmylocationtoserver(client), 0, 5000);
      Looper.prepare();
      // Toast.makeText(MapsActivity.this, "Waiting for server", Toast.LENGTH_LONG).show();
      Log.e("msg", "Waiting for server");

      int i = 10;
      while (i-- > 0) {
        InputStream iStream;
        ObjectInputStream oiStream;
        if (client != null) {
          Log.e("Hey", "Still waiting");
          Log.e("client", "client ip " + client.getInetAddress().toString());
          try {
            iStream = client.getInputStream();
            oiStream = new ObjectInputStream(iStream);
            try {

              if (oiStream == null) Log.e("oistream", "null");
              else {
                servHash = (HashMap<String, LinkedList>) oiStream.readObject();
                updateHash();
                // updatemarkers();
                System.out.println("Got from server***************");
              }
            } catch (ClassNotFoundException e) {
              Log.e("CnotF", "Exception");
              e.printStackTrace();
            }

          } catch (IOException e) {
            Log.e("IOE", "IO exception ");
            e.printStackTrace();
          }

        } else {
          Log.e("err", "failed failed");
        }
      }
    }
예제 #21
0
  /**
   * 启动服务端
   *
   * @author LiZhiXian
   * @version 1.0
   * @date 2015-12-23 上午10:21:05
   */
  public void start() {

    try {
      ServerSocket server = new ServerSocket(port);
      while (true) { // 允许多个客户端接入
        Socket socket = server.accept(); // 等待客户端接入
        socket.setKeepAlive(true);
        System.out.println("有个客户端请求连接...");
        new Thread(new RequestHandle(socket)).start();
      }
    } catch (IOException e) {
      System.out.println("服务端启动失败.....");
      e.printStackTrace();
    }
  }
 /**
  * Sets the SelectionKey of this handler.
  *
  * <p>Use EITHER this method or connect, not both.
  *
  * @param k the java.nio.channels#SelectionKey attaching this handler
  * @return this NetworkEventHandler, to call more methods on
  */
 @SuppressWarnings("unchecked")
 @Override
 protected SocketServerEventHandler setSelectionKey(SelectionKey k) {
   try {
     super.setSelectionKey(k);
     Socket socket = ((SocketChannel) selectionKey.channel()).socket();
     remoteAddress = socket.getRemoteSocketAddress();
     socket.setKeepAlive(true);
     server
         .getHandlerByAddress()
         .put(((SocketChannel) selectionKey.channel()).socket().getRemoteSocketAddress(), this);
     return this;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
예제 #23
0
  /**
   * Applies the current settings to the given socket.
   *
   * @param s Socket to apply the settings to
   * @return Socket the input socket
   */
  protected Socket applySettings(Socket s) {
    try {
      s.setKeepAlive(SO_KEEPALIVE);
      s.setOOBInline(OOBINLINE);
      s.setReuseAddress(SO_REUSEADDR);
      s.setTcpNoDelay(TCP_NODELAY);
      s.setOOBInline(OOBINLINE);

      s.setReceiveBufferSize(SO_RCVBUF);
      s.setSendBufferSize(SO_SNDBUF);
      s.setSoTimeout(SO_TIMEOUT);
      s.setSoLinger(SO_LINGER, LINGER);
    } catch (SocketException e) {
      throw new RuntimeException(e);
    }
    return s;
  }
예제 #24
0
  public void createHost(String addressStr) {
    // long SLEEP_TIME = 500; // .5 second.

    centralRegistry = new CentralRegistry();

    String msg = "Ready to host at " + addressStr + "\nWaiting for clients to connect...";
    Platform.runLater(
        () -> {
          // if (mainMenu != null)
          createAlert(msg);
        });

    try {
      ss = new ServerSocket(port); // , 0);// InetAddress.getByAddress(new byte[] {127,0,0,1}));
      /*
       * Allows the socket to be bound even though a previous
       * connection is in a timeout state.
       */
      ss.setReuseAddress(true);

      while (!serverStopped) {
        logger.info("Waiting for clients to connect...");
        socket = ss.accept();
        socket.setKeepAlive(true);
        connectionTask = new ConnectionTask(socket);
        connectionTaskExecutor.execute(connectionTask);
        // Thread t = new Thread(new ConnectionThread(socket));
        // t.start();
        // try {
        // TimeUnit.MILLISECONDS.sleep(SLEEP_TIME);
        // } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        //	e.printStackTrace();
        // }
      }

      // } catch (BindException e) {
      //	System.err.println("server socket already running.");
      //   System.exit(1);
    } catch (IOException e) {
      System.err.println("Unexpected error.");
      e.printStackTrace();
      System.exit(2);
    }
  }
예제 #25
0
  /**
   * @param url
   * @param request
   * @param resContentHeaders
   * @param timeout
   * @return
   * @throws java.lang.Exception
   * @deprecated As of proxy release 1.0.10, replaced by {@link #sendRequestToUrl( boolean isBusReq,
   *     URL url, String request, Map resContentHeaders, int timeout)}
   */
  public static String sendRequestOverHTTP(
      URL url, String request, Map resContentHeaders, int timeout) throws Exception {
    // setup network connectivity details
    String ipAddress = url.getHost();
    int port = url.getPort();
    if (port <= 0) {
      port = 80; // default to port 80
    }
    String ctx = url.getPath();

    // setup socket
    Socket socket = new Socket(ipAddress, port);
    socket.setKeepAlive(true); // activate a TCP heartbeat
    socket.setSoTimeout(timeout);

    // tx request
    String encodedString = URLEncoder.encode(request);
    BufferedOutputStream out =
        new BufferedOutputStream(socket.getOutputStream(), OUTPUT_BUFFER_LEN);
    out.write(generateRequest(ipAddress, port, ctx, encodedString.length()).getBytes());
    out.write(FastHttpClientConstants.HTTP_REQUEST_POST_KEY.getBytes());
    out.write(encodedString.getBytes());
    out.flush();

    // recv response
    BufferedInputStream in = new BufferedInputStream(socket.getInputStream(), INPUT_BUFFER_LEN);
    StringBuilder buffy = new StringBuilder(INPUT_BUFFER_LEN);
    int ch = 0;
    while ((ch = in.read()) > -1) {
      buffy.append((char) ch);
    }
    out.close();
    in.close();
    socket.close();

    // determine if response was chunked by the server or not
    String fullResponse = buffy.toString();

    populateHTTPHeaderContentMap(fullResponse, resContentHeaders);

    if (fullResponse.contains(FastHttpClientConstants.HTTP_REQUEST_CHUNKED)) {
      return getChunkedResponseBody(fullResponse);
    }
    return getNonChunkedResponseBody(fullResponse);
  }
 /**
  * Sets socket attributes on the socket.
  *
  * @param socket The socket.
  * @throws SocketException
  */
 protected void setSocketAttributes(Socket socket) throws SocketException {
   if (this.soTimeout >= 0) {
     socket.setSoTimeout(this.soTimeout);
   }
   if (this.soSendBufferSize > 0) {
     socket.setSendBufferSize(this.soSendBufferSize);
   }
   if (this.soReceiveBufferSize > 0) {
     socket.setReceiveBufferSize(this.soReceiveBufferSize);
   }
   socket.setTcpNoDelay(this.soTcpNoDelay);
   if (this.soLinger >= 0) {
     socket.setSoLinger(true, this.soLinger);
   }
   if (this.soTrafficClass >= 0) {
     socket.setTrafficClass(this.soTrafficClass);
   }
   socket.setKeepAlive(this.soKeepAlive);
 }
예제 #27
0
파일: TSocket.java 프로젝트: yakolla/thrift
  /**
   * Constructor that takes an already created socket.
   *
   * @param socket Already created socket object
   * @throws TTransportException if there is an error setting up the streams
   */
  public TSocket(Socket socket) throws TTransportException {
    socket_ = socket;
    try {
      socket_.setSoLinger(false, 0);
      socket_.setTcpNoDelay(true);
      socket_.setKeepAlive(true);
    } catch (SocketException sx) {
      LOGGER.warn("Could not configure socket.", sx);
    }

    if (isOpen()) {
      try {
        inputStream_ = new BufferedInputStream(socket_.getInputStream(), 1024);
        outputStream_ = new BufferedOutputStream(socket_.getOutputStream(), 1024);
      } catch (IOException iox) {
        close();
        throw new TTransportException(TTransportException.NOT_OPEN, iox);
      }
    }
  }
예제 #28
0
  protected void setSocketParameters(Socket client_sock) throws SocketException {
    try {
      client_sock.setSendBufferSize(server.send_buf_size);
    } catch (IllegalArgumentException ex) {
      server.log.error(
          "%s: exception setting send buffer to %d bytes: %s",
          server.local_addr, server.send_buf_size, ex);
    }
    try {
      client_sock.setReceiveBufferSize(server.recv_buf_size);
    } catch (IllegalArgumentException ex) {
      server.log.error(
          "%s: exception setting receive buffer to %d bytes: %s",
          server.local_addr, server.recv_buf_size, ex);
    }

    client_sock.setKeepAlive(true);
    client_sock.setTcpNoDelay(server.tcp_nodelay);
    if (server.linger > 0) client_sock.setSoLinger(true, server.linger);
    else client_sock.setSoLinger(false, -1);
  }
예제 #29
0
 /** open real socket and set time out when waitForAck is enabled is socket open return directly */
 protected void openSocket() throws IOException {
   if (isConnected()) return;
   try {
     socket = new Socket();
     InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort());
     socket.connect(sockaddr, (int) getTimeout());
     socket.setSendBufferSize(getTxBufSize());
     socket.setReceiveBufferSize(getRxBufSize());
     socket.setSoTimeout((int) getTimeout());
     socket.setTcpNoDelay(getTcpNoDelay());
     socket.setKeepAlive(getSoKeepAlive());
     socket.setReuseAddress(getSoReuseAddress());
     socket.setOOBInline(getOoBInline());
     socket.setSoLinger(getSoLingerOn(), getSoLingerTime());
     socket.setTrafficClass(getSoTrafficClass());
     setConnected(true);
     soOut = socket.getOutputStream();
     soIn = socket.getInputStream();
     setRequestCount(0);
     setConnectTime(System.currentTimeMillis());
     if (log.isDebugEnabled())
       log.debug(
           sm.getString(
               "IDataSender.openSocket",
               getAddress().getHostAddress(),
               new Integer(getPort()),
               new Long(0)));
   } catch (IOException ex1) {
     SenderState.getSenderState(getDestination()).setSuspect();
     if (log.isDebugEnabled())
       log.debug(
           sm.getString(
               "IDataSender.openSocket.failure",
               getAddress().getHostAddress(),
               new Integer(getPort()),
               new Long(0)),
           ex1);
     throw (ex1);
   }
 }
 private Socket connect() {
   Socket socket = null;
   int attempts = 0;
   do {
     attempts++;
     try {
       socket = new Socket(Utils.REGISTRAR_ADDR, Utils.REGISTRAR_PORT);
       socket.setKeepAlive(true);
       socket.setSoTimeout(0);
     } catch (Exception e) {
       String msg =
           String.format("Warning: connection attempt %d failed at %s.", attempts, this.getInfo());
       System.err.println(msg);
       System.err.println(e.getMessage());
       try {
         Thread.sleep(random.nextInt(100) + 1); /* [0..100] + 1 > 0. */
       } catch (InterruptedException ignored) {
       }
     }
   } while (socket == null);
   return socket;
 }