コード例 #1
1
  private HttpConnection(Address config, int connectTimeout) throws IOException {
    this.address = config;

    /*
     * Try each of the host's addresses for best behaviour in mixed IPv4/IPv6
     * environments. See http://b/2876927
     * TODO: add a hidden method so that Socket.tryAllAddresses can does this for us
     */
    Socket socketCandidate = null;

    /*
     * For specific proxy ipaddress such as APN access point(wap gateway ip)
     * could not be resolved as network hostname,then the config.socketHost will
     * be the string 'not-a-legal-address'.
     * Try using the address directly.
     * @mod by spreadsoft b
     * */
    if (config.socketHost.equals("not-a-legal-address")
        && config.proxy != null
        && config.proxy.address() != null
        && config.proxy.type() == Proxy.Type.HTTP) {

      System.out.println(
          "The proxy can not be resolved as hostname:"
              + config.proxy.address().toString()
              + ",try use the address directly ");
      try {
        socketCandidate = new Socket();
        socketCandidate.connect((InetSocketAddress) config.proxy.address(), connectTimeout);
      } catch (IOException e) {
        System.out.println("The proxy address stil could not be used.");
        throw e;
      }
    } else {
      InetAddress[] addresses = InetAddress.getAllByName(config.socketHost);
      for (int i = 0; i < addresses.length; i++) {
        try {
          socketCandidate =
              (config.proxy != null && config.proxy.type() != Proxy.Type.HTTP)
                  ? new Socket(config.proxy)
                  : new Socket();
          socketCandidate.connect(
              new InetSocketAddress(addresses[i], config.socketPort), connectTimeout);
          break;
        } catch (IOException e) {
          if (i == addresses.length - 1) {
            throw e;
          }
        }
      }
    }
    /* @mod by spreadsoft e */
    this.socket = socketCandidate;
  }
コード例 #2
0
ファイル: TcpTransport.java プロジェクト: gerring/daq-eclipse
  protected void connect() throws Exception {

    if (socket == null && socketFactory == null) {
      throw new IllegalStateException(
          "Cannot connect if the socket or socketFactory have not been set");
    }

    InetSocketAddress localAddress = null;
    InetSocketAddress remoteAddress = null;

    if (localLocation != null) {
      localAddress =
          new InetSocketAddress(
              InetAddress.getByName(localLocation.getHost()), localLocation.getPort());
    }

    if (remoteLocation != null) {
      String host = resolveHostName(remoteLocation.getHost());
      remoteAddress = new InetSocketAddress(host, remoteLocation.getPort());
    }
    // Set the traffic class before the socket is connected when possible so
    // that the connection packets are given the correct traffic class.
    this.trafficClassSet = setTrafficClass(socket);

    if (socket != null) {

      if (localAddress != null) {
        socket.bind(localAddress);
      }

      // If it's a server accepted socket.. we don't need to connect it
      // to a remote address.
      if (remoteAddress != null) {
        if (connectionTimeout >= 0) {
          socket.connect(remoteAddress, connectionTimeout);
        } else {
          socket.connect(remoteAddress);
        }
      }

    } else {
      // For SSL sockets.. you can't create an unconnected socket :(
      // This means the timout option are not supported either.
      if (localAddress != null) {
        socket =
            socketFactory.createSocket(
                remoteAddress.getAddress(), remoteAddress.getPort(),
                localAddress.getAddress(), localAddress.getPort());
      } else {
        socket = socketFactory.createSocket(remoteAddress.getAddress(), remoteAddress.getPort());
      }
    }

    initialiseSocket(socket);
    initializeStreams();
  }
コード例 #3
0
  @Test
  public void testGETThenNoContentFromTwoClients() throws Exception {
    InetSocketAddress proxyAddress =
        startProxy(
            startServer(
                new ServerSessionFrameListener.Adapter() {
                  @Override
                  public StreamFrameListener onSyn(Stream stream, SynInfo synInfo) {
                    Assert.assertTrue(synInfo.isClose());
                    Fields requestHeaders = synInfo.getHeaders();
                    Assert.assertNotNull(requestHeaders.get("via"));

                    Fields responseHeaders = new Fields();
                    responseHeaders.put(HTTPSPDYHeader.VERSION.name(version), "HTTP/1.1");
                    responseHeaders.put(HTTPSPDYHeader.STATUS.name(version), "200 OK");
                    ReplyInfo replyInfo = new ReplyInfo(responseHeaders, true);
                    stream.reply(replyInfo, new Callback.Adapter());
                    return null;
                  }
                }));

    Socket client1 = new Socket();
    client1.connect(proxyAddress);
    OutputStream output1 = client1.getOutputStream();

    String request =
        "" + "GET / HTTP/1.1\r\n" + "Host: localhost:" + proxyAddress.getPort() + "\r\n" + "\r\n";
    output1.write(request.getBytes("UTF-8"));
    output1.flush();

    InputStream input1 = client1.getInputStream();
    BufferedReader reader1 = new BufferedReader(new InputStreamReader(input1, "UTF-8"));
    String line = reader1.readLine();
    Assert.assertTrue(line.contains(" 200"));
    while (line.length() > 0) line = reader1.readLine();
    Assert.assertFalse(reader1.ready());

    // Perform another request with another client
    Socket client2 = new Socket();
    client2.connect(proxyAddress);
    OutputStream output2 = client2.getOutputStream();

    output2.write(request.getBytes("UTF-8"));
    output2.flush();

    InputStream input2 = client2.getInputStream();
    BufferedReader reader2 = new BufferedReader(new InputStreamReader(input2, "UTF-8"));
    line = reader2.readLine();
    Assert.assertTrue(line.contains(" 200"));
    while (line.length() > 0) line = reader2.readLine();
    Assert.assertFalse(reader2.ready());

    client1.close();
    client2.close();
  }
コード例 #4
0
 /**
  * Attempts to get a new socket connection to the given host within the given time limit.
  *
  * <p>To circumvent the limitations of older JREs that do not support connect timeout a controller
  * thread is executed. The controller thread attempts to create a new socket within the given
  * limit of time. If socket constructor does not return until the timeout expires, the controller
  * terminates and throws an {@link ConnectTimeoutException}
  *
  * @param host the host name/IP
  * @param port the port on the host
  * @param localAddress the local host name/IP to bind the socket to
  * @param localPort the port on the local machine
  * @param params {@link HttpConnectionParams Http connection parameters}
  * @return Socket a new socket
  * @throws IOException if an I/O error occurs while creating the socket
  * @throws UnknownHostException if the IP address of the host cannot be determined
  */
 @Override
 public Socket createSocket(
     final String host,
     final int port,
     final InetAddress localAddress,
     final int localPort,
     final HttpConnectionParams params)
     throws IOException, UnknownHostException, ConnectTimeoutException {
   if (params == null) {
     throw new IllegalArgumentException("Parameters may not be null");
   }
   int timeout = params.getConnectionTimeout();
   SocketFactory socketfactory = getSSLContext().getSocketFactory();
   if (timeout == 0) {
     Socket socket = socketfactory.createSocket(host, port, localAddress, localPort);
     if (socket instanceof SSLSocket) {
       ((SSLSocket) socket)
           .setEnabledProtocols(
               SSLUtils.getSupportedProtocols(((SSLSocket) socket).getEnabledProtocols()));
     }
     return socket;
   } else {
     Socket socket = socketfactory.createSocket();
     if (socket instanceof SSLSocket) {
       ((SSLSocket) socket)
           .setEnabledProtocols(
               SSLUtils.getSupportedProtocols(((SSLSocket) socket).getEnabledProtocols()));
     }
     SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
     SocketAddress remoteaddr = new InetSocketAddress(host, port);
     socket.bind(localaddr);
     socket.connect(remoteaddr, timeout);
     return socket;
   }
 }
コード例 #5
0
ファイル: SphinxClient.java プロジェクト: nzinfo/csft5
  /** Internal method. Connect to searchd and exchange versions. */
  private Socket _Connect() {
    if (_socket != null) return _socket;

    _connerror = false;
    Socket sock = null;
    try {
      sock = new Socket();
      sock.setSoTimeout(_timeout);
      InetSocketAddress addr = new InetSocketAddress(_host, _port);
      sock.connect(addr, _timeout);

      DataInputStream sIn = new DataInputStream(sock.getInputStream());
      int version = sIn.readInt();
      if (version < 1) {
        sock.close();
        _error = "expected searchd protocol version 1+, got version " + version;
        return null;
      }

      DataOutputStream sOut = new DataOutputStream(sock.getOutputStream());
      sOut.writeInt(VER_MAJOR_PROTO);

    } catch (IOException e) {
      _error = "connection to " + _host + ":" + _port + " failed: " + e;
      _connerror = true;

      try {
        if (sock != null) sock.close();
      } catch (IOException e1) {
      }
      return null;
    }

    return sock;
  }
コード例 #6
0
ファイル: JSocket.java プロジェクト: gspandy/AMI_FEP
 private boolean _connect() {
   try {
     trace.trace("client socket is connecting to server :" + this.getPeerAddr());
     lastConnectTime = System.currentTimeMillis();
     socket = new Socket();
     InetSocketAddress ar = new InetSocketAddress(hostIp, hostPort);
     socket.setSoTimeout(timeout * 1000);
     socket.connect(ar, timeout * 1000);
     connectWaitTime = 2;
   } catch (ConnectException e) {
     log.error(
         "Can't connect to:" + hostIp + "@" + hostPort + ",reason=" + e.getLocalizedMessage());
     socket = null;
     return false;
   } catch (Exception e) {
     log.error("Can't connect to:" + hostIp + "@" + hostPort);
     if (null != socket) {
       try {
         socket.close();
       } catch (Exception e1) {
       }
     }
     socket = null;
     return false;
   }
   log.info("client socket connect to server successfully:" + this.getPeerAddr());
   return true;
 }
コード例 #7
0
  @Test
  public void testConnectCancellation() throws Throwable {
    // Check if the test can be executed or should be skipped because of no network/internet
    // connection
    // See https://github.com/netty/netty/issues/1474
    boolean badHostTimedOut = true;
    Socket socket = new Socket();
    try {
      socket.connect(new InetSocketAddress(BAD_HOST, BAD_PORT), 10);
    } catch (ConnectException e) {
      badHostTimedOut = false;
      // is thrown for no route to host when using Socket connect
    } catch (Exception e) {
      // ignore
    } finally {
      try {
        socket.close();
      } catch (IOException e) {
        // ignore
      }
    }

    assumeThat(
        "The connection attempt to " + BAD_HOST + " does not time out.", badHostTimedOut, is(true));

    run();
  }
コード例 #8
0
    @Override
    public void run() {
      Socket socket = new Socket();
      InetSocketAddress address = new InetSocketAddress(this.peer.getIp(), this.peer.getPort());

      try {
        logger.info("Connecting to {}...", this.peer);
        socket.connect(address, 3 * 1000);

        this.handler.sendHandshake(socket);
        Handshake hs =
            this.handler.validateHandshake(
                socket, (this.peer.hasPeerId() ? this.peer.getPeerId().array() : null));
        logger.info(
            "Handshaked with {}, peer ID is {}.",
            this.peer,
            Torrent.byteArrayToHexString(hs.getPeerId()));
        this.handler.fireNewPeerConnection(socket, hs.getPeerId());
      } catch (IOException ioe) {
        try {
          socket.close();
        } catch (IOException e) {
        }
        this.handler.fireFailedConnection(this.peer, ioe);
      } catch (ParseException pe) {
        try {
          socket.close();
        } catch (IOException e) {
        }
        this.handler.fireFailedConnection(this.peer, pe);
      }
    }
コード例 #9
0
ファイル: NetworkThread.java プロジェクト: djkazic/jdrone
 public NetworkThread(String server, String channel, int port) {
   try {
     this.channel = channel;
     if (Settings.ssl) {
       SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
       socket = (SSLSocket) sslsocketfactory.createSocket();
       List<String> limited = new LinkedList<String>();
       for (String suite : ((SSLSocket) socket).getEnabledCipherSuites()) {
         if (!suite.contains("_DHE_")) {
           limited.add(suite);
         }
       }
       ((SSLSocket) socket).setEnabledCipherSuites(limited.toArray(new String[limited.size()]));
       socket.connect(new InetSocketAddress(server, port));
     } else {
       socket = new Socket(server, port);
     }
     writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
     reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     uc = new Utilities();
     line = null;
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #10
0
  private void startSlave() {
    try {
      hostConn.connect(
          new InetSocketAddress(ConnectionSettings.HOST, ConnectionSettings.HOST_PORT));
      L.dbg("Slave connected to " + ConnectionSettings.HOST + " : " + ConnectionSettings.HOST_PORT);
    } catch (IOException e) {
      e.printStackTrace();
    }

    BufferedReader serverReader = null;
    try {
      serverReader = new BufferedReader(new InputStreamReader(hostConn.getInputStream()));
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    String incoming = "first null message";

    try {
      while ((incoming = serverReader.readLine()) != null) {
        L.dbg("Got from server: " + incoming);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #11
0
ファイル: HTTPServer.java プロジェクト: kailIII/apjp
  protected synchronized void stopHTTPServer() throws HTTPServerException {
    logger.log(2, "HTTP_SERVER/STOP_HTTP_SERVER");

    try {
      thread = null;

      try {
        Socket outputSocket = new Socket();
        outputSocket.connect(
            new InetSocketAddress(
                APJP.APJP_LOCAL_HTTP_SERVER_ADDRESS, serverSocket.getLocalPort()));
        outputSocket.close();
      } catch (Exception e) {

      }

      try {
        serverSocket.close();
      } catch (Exception e) {

      }
    } catch (Exception e) {
      logger.log(2, "HTTP_SERVER/STOP_HTTP_SERVER: EXCEPTION", e);

      throw new HTTPServerException("HTTP_SERVER/STOP_HTTP_SERVER", e);
    }
  }
コード例 #12
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");
   }
 }
コード例 #13
0
ファイル: ClientTCP.java プロジェクト: hwiba/scouter
  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);
    }
  }
コード例 #14
0
ファイル: TestSocket.java プロジェクト: stxyg/demo
  public static void main(String[] args) throws IOException {
    Socket s = new Socket();
    s.connect(new InetSocketAddress("www.meizu.com", 80), 2000);
    // s.setSoTimeout(2000);
    boolean b = s.isConnected();
    System.out.println(b);
    if (b) {
      InputStream in = s.getInputStream();
      System.out.println(in);
      Scanner scanner = new Scanner(in);
      byte[] buf = new byte[1024];
      System.out.println(in.available());
      System.out.println((in.read(buf) != -1));
      while (in.read(buf) != -1) {
        System.out.println("in...");
        System.out.println(buf);
      }

      while (scanner.hasNext()) {
        System.out.println("有数据。。。。");
        String next = scanner.nextLine();

        System.out.println(next);
      }
      s.close();
      if (s.isClosed()) {
        System.out.println("套接字已经关闭");
      }
    }
  }
コード例 #15
0
  @Override
  public void onCreate() {
    Log.i(TAG, "inside onCreate - Creating Socket");
    super.onCreate();
    if (mSocket == null || mSocket.isClosed()) {
      try {
        // mSocket = new Socket(InetAddress.getByName("localhost"), 7201);
        mSocket = new Socket();
        Log.d(TAG, "Opening client socket - ");
        mSocket.bind(null);

        mSocket.connect(
            (new InetSocketAddress(
                getString(R.string.queue_server_dns),
                getResources().getInteger(R.integer.next_token_port))),
            SOCKET_TIMEOUT);

        Log.d(TAG, "Client socket - " + mSocket.isConnected());
        assert mSocket != null;
        mDataInputStream = new DataInputStream(mSocket.getInputStream());
        Log.i(TAG, "Socket Created, Stream Opened");
      } catch (UnknownHostException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (IOException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      }
    }
  }
コード例 #16
0
ファイル: Channel.java プロジェクト: shshen/gondola
 public void connect() throws Exception {
   socket = new Socket();
   socket.connect(new InetSocketAddress(host, port), timeout);
   socket.setSoTimeout(timeout);
   rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
 }
コード例 #17
0
 public static boolean tryToConnect(InetAddress fromAddress, SocketAddress toSocket, int timeout)
     throws IOException {
   if (LOG.isDebugEnabled()) {
     LOG.debug(
         "Trying to connect to JobManager ("
             + toSocket
             + ") from local address "
             + fromAddress
             + " with timeout "
             + timeout);
   }
   boolean connectable = true;
   Socket socket = null;
   try {
     socket = new Socket();
     SocketAddress bindP =
         new InetSocketAddress(fromAddress, 0); // 0 = let the OS choose the port on this
     // machine
     socket.bind(bindP);
     socket.connect(toSocket, timeout);
   } catch (Exception ex) {
     LOG.info("Failed to determine own IP address from '" + fromAddress + "': " + ex.getMessage());
     if (LOG.isDebugEnabled()) {
       LOG.debug("Failed with exception", ex);
     }
     connectable = false;
   } finally {
     if (socket != null) {
       socket.close();
     }
   }
   return connectable;
 }
コード例 #18
0
 @Override
 public Socket createSocket(
     final String host,
     final int port,
     final InetAddress localAddress,
     final int localPort,
     final HttpConnectionParams params)
     throws IOException, UnknownHostException, ConnectTimeoutException {
   final int timeout = params.getConnectionTimeout();
   if (timeout == 0) {
     Socket socket = createSocket(host, port, localAddress, localPort);
     if (socket instanceof SSLSocket) {
       ((SSLSocket) socket)
           .setEnabledProtocols(
               SSLUtils.getSupportedProtocols(((SSLSocket) socket).getEnabledProtocols()));
     }
     return socket;
   } else {
     final Socket s = ssf.createSocket();
     if (s instanceof SSLSocket) {
       ((SSLSocket) s)
           .setEnabledProtocols(
               SSLUtils.getSupportedProtocols(((SSLSocket) s).getEnabledProtocols()));
     }
     s.bind(new InetSocketAddress(localAddress, localPort));
     s.connect(new InetSocketAddress(host, port), timeout);
     return s;
   }
 }
コード例 #19
0
ファイル: ClientSession.java プロジェクト: JosuaKrause/basex
  /**
   * Constructor, specifying the server host:port combination, login data and an output stream.
   *
   * @param host server name
   * @param port server port
   * @param user user name
   * @param pass password
   * @param output client output; if set to {@code null}, results will be returned as strings.
   * @throws IOException I/O exception
   */
  public ClientSession(
      final String host,
      final int port,
      final String user,
      final String pass,
      final OutputStream output)
      throws IOException {

    super(output);
    ehost = host;
    socket = new Socket();
    try {
      // limit timeout to five seconds
      socket.connect(new InetSocketAddress(host, port), 5000);
    } catch (final IllegalArgumentException ex) {
      throw new BaseXException(ex);
    }
    sin = socket.getInputStream();

    // receive timestamp
    final BufferInput bi = new BufferInput(sin);
    final String ts = bi.readString();

    // send user name and hashed password/timestamp
    sout = PrintOutput.get(socket.getOutputStream());
    send(user);
    send(Token.md5(Token.md5(pass) + ts));
    sout.flush();

    // receive success flag
    if (!ok(bi)) throw new LoginException();
  }
コード例 #20
0
ファイル: ClientSocket.java プロジェクト: Tony-YI/home_page
 public void createConnection() {
   try {
     Log.v("1111", "1111");
     socket2 = new Socket();
     Log.v("2222", "2222");
     socket2.connect(new InetSocketAddress(ip, port), 15 * 1000);
     Log.v("3333", "3333");
   } catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     if (socket2 != null) {
       try {
         socket2.close();
       } catch (IOException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
       }
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     if (socket2 != null) {
       try {
         socket2.close();
       } catch (IOException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
       }
     }
   } finally {
   }
 }
コード例 #21
0
  protected Socket borrowSocket() throws IOException {
    Socket socket = socketBlockingQueue.poll();

    if (socket != null) {
      if (socket.isClosed()
          || !socket.isConnected()
          || socket.isInputShutdown()
          || socket.isOutputShutdown()) {

        try {
          socket.close();
        } catch (IOException ioe) {
          if (_log.isWarnEnabled()) {
            _log.warn(ioe, ioe);
          }
        }

        socket = null;
      }
    }

    if (socket == null) {
      socket = new Socket();

      socket.connect(socketAddress);
    }

    return socket;
  }
コード例 #22
0
ファイル: TSocket.java プロジェクト: yakolla/thrift
  /** Connects the socket, creating a new socket object if necessary. */
  public void open() throws TTransportException {
    if (isOpen()) {
      throw new TTransportException(TTransportException.ALREADY_OPEN, "Socket already connected.");
    }

    if (host_.length() == 0) {
      throw new TTransportException(TTransportException.NOT_OPEN, "Cannot open null host.");
    }
    if (port_ <= 0) {
      throw new TTransportException(TTransportException.NOT_OPEN, "Cannot open without port.");
    }

    if (socket_ == null) {
      initSocket();
    }

    try {
      socket_.connect(new InetSocketAddress(host_, port_), timeout_);
      inputStream_ = new BufferedInputStream(socket_.getInputStream(), 1024);
      outputStream_ = new BufferedOutputStream(socket_.getOutputStream(), 1024);
    } catch (IOException iox) {
      close();
      throw new TTransportException(TTransportException.NOT_OPEN, iox);
    }
  }
コード例 #23
0
ファイル: TcpPipe.java プロジェクト: alphazero/jacomecha
    @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");
      }
    }
コード例 #24
0
  /**
   * Try to establish a connection to server with id sid.
   *
   * @param sid server id
   */
  synchronized void connectOne(long sid) {
    if (senderWorkerMap.get(sid) == null) {
      InetSocketAddress electionAddr;
      if (self.quorumPeers.containsKey(sid)) {
        electionAddr = self.quorumPeers.get(sid).electionAddr;
      } else {
        LOG.warn("Invalid server id: " + sid);
        return;
      }
      try {

        if (LOG.isDebugEnabled()) {
          LOG.debug("Opening channel to server " + sid);
        }
        Socket sock = new Socket();
        setSockOpts(sock);
        sock.connect(self.getView().get(sid).electionAddr, cnxTO);
        if (LOG.isDebugEnabled()) {
          LOG.debug("Connected to server " + sid);
        }
        initiateConnection(sock, sid);
      } catch (UnresolvedAddressException e) {
        // Sun doesn't include the address that causes this
        // exception to be thrown, also UAE cannot be wrapped cleanly
        // so we log the exception in order to capture this critical
        // detail.
        LOG.warn("Cannot open channel to " + sid + " at election address " + electionAddr, e);
        throw e;
      } catch (IOException e) {
        LOG.warn("Cannot open channel to " + sid + " at election address " + electionAddr, e);
      }
    } else {
      LOG.debug("There is a connection already for server " + sid);
    }
  }
コード例 #25
0
ファイル: TCPClient.java プロジェクト: daeun9205/network
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Socket socket = null;
    try {

      socket = new Socket();
      System.out.println("[클라이언트] 연결 요청");
      socket.connect(new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT));
      System.out.println("[클라이언트] 연결 성공");

      // 쓰고 받기
      OutputStream os = socket.getOutputStream();
      InputStream is = socket.getInputStream();

      String data = "Hello World\n";
      os.write(data.getBytes("UTF-8"));

      byte[] buffer = new byte[128];
      int readByteCount = is.read(buffer);
      data = new String(buffer, 0, readByteCount, "UTF-8");
      System.out.println("[클라이언트] 데이터 수신 : " + data);

      if (socket.isClosed() == false) {
        socket.close(); // 소켓을 닫으면 -1반환
      }
      // socket.close();

    } catch (IOException ex) {
      System.out.println("[클라이언트] 에러" + ex);
    }
  }
コード例 #26
0
	public static boolean isReachable(InetAddress localInetAddr, InetAddress remoteInetAddr,int port, int timeout) { 
		
		boolean isReachable = false; 
		Socket socket = null; 
		try{ 
		 socket = new Socket(); 
		 // 端口号设置为 0 表示在本地挑选一个可用端口进行连接
		 SocketAddress localSocketAddr = new InetSocketAddress(localInetAddr, 0); 
		 socket.bind(localSocketAddr); 
		 InetSocketAddress endpointSocketAddr = new InetSocketAddress(remoteInetAddr, port); 
		 socket.connect(endpointSocketAddr, timeout);        
		 System.out.println("SUCCESS - connection established! Local: " + 
				 			localInetAddr.getHostAddress() + " remote: " + 
				 			remoteInetAddr.getHostAddress() + " port" + port); 
		 isReachable = true; 
		} catch(IOException e) { 
		 System.out.println("FAILRE - CAN not connect! Local: " + 
				 	localInetAddr.getHostAddress() + " remote: " + 
				 	remoteInetAddr.getHostAddress() + " port" + port); 
		} finally{ 
		 if(socket != null) { 
		 try{ 
		 socket.close(); 
		 } catch(IOException e) { 
		    System.out.println("Error occurred while closing socket.."); 
		   } 
		 } 
		} 
		return isReachable; 
	}
コード例 #27
0
 public static boolean validateProxy(HttpHost p) {
   if (localAddr == null) {
     logger.error("cannot get local IP");
     return false;
   }
   boolean isReachable = false;
   Socket socket = null;
   try {
     socket = new Socket();
     socket.bind(new InetSocketAddress(localAddr, 0));
     InetSocketAddress endpointSocketAddr =
         new InetSocketAddress(p.getAddress().getHostAddress(), p.getPort());
     socket.connect(endpointSocketAddr, 3000);
     logger.debug(
         "SUCCESS - connection established! Local: "
             + localAddr.getHostAddress()
             + " remote: "
             + p);
     isReachable = true;
   } catch (IOException e) {
     logger.warn(
         "FAILRE - CAN not connect! Local: " + localAddr.getHostAddress() + " remote: " + p);
   } finally {
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException e) {
         logger.warn("Error occurred while closing socket of validating proxy", e);
       }
     }
   }
   return isReachable;
 }
コード例 #28
0
ファイル: NetUtils.java プロジェクト: kanishin/Lealone
 /**
  * Create a client socket that is connected to the given address and port.
  *
  * @param address the address to connect to
  * @param port the port
  * @param ssl if SSL should be used
  * @return the socket
  */
 public static Socket createSocket(InetAddress address, int port, boolean ssl) throws IOException {
   long start = System.currentTimeMillis();
   for (int i = 0; ; i++) {
     try {
       if (ssl) {
         return CipherFactory.createSocket(address, port);
       }
       Socket socket = new Socket();
       socket.connect(new InetSocketAddress(address, port), SysProperties.SOCKET_CONNECT_TIMEOUT);
       return socket;
     } catch (IOException e) {
       if (System.currentTimeMillis() - start >= SysProperties.SOCKET_CONNECT_TIMEOUT) {
         // either it was a connect timeout,
         // or list of different exceptions
         throw e;
       }
       if (i >= SysProperties.SOCKET_CONNECT_RETRY) {
         throw e;
       }
       // wait a bit and retry
       try {
         // sleep at most 256 ms
         long sleep = Math.min(256, i * i);
         Thread.sleep(sleep);
       } catch (InterruptedException e2) {
         // ignore
       }
     }
   }
 }
コード例 #29
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);
 }
コード例 #30
0
  @Override
  protected void onHandleIntent(Intent intent) {

    if (intent.getAction().equals(ACTION_SEND_MESSAGE)) {
      String messageString = intent.getExtras().getString(EXTRAS_MESSSGE_STRING);
      String host = intent.getExtras().getString(EXTRAS_ADDRESS);
      Socket socket = new Socket();
      int port = intent.getExtras().getInt(EXTRAS_PORT);

      try {
        Log.d("MessageTransferService", "Opening client socket - host: " + host);
        socket.bind(null);
        socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
        Log.d("MessageTransferService", "Client socket - " + socket.isConnected());
        OutputStream os = socket.getOutputStream();
        byte[] stringByte = messageString.getBytes();
        os.write(stringByte);
        os.close();
        Log.d("MessageTransferService", "Client: Data written");
      } catch (IOException e) {
        Log.e("MessageTransferService", e.getMessage());
      } finally {
        if (socket != null) {
          if (socket.isConnected()) {
            try {
              socket.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
  }