Java Code Examples for java.net.Socket.connect()

The following are Jave code examples for showing how to use connect() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Equella   File: EasySSLProtocolSocketFactory.java   Source Code and License Vote up 6 votes
/**
 * 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}
 * </p>
 * 
 * @param host the host name/IP
 * @param port the port on the host
 * @param clientHost the local host name/IP to bind the socket to
 * @param clientPort 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 )
	{
		return socketfactory.createSocket(host, port, localAddress, localPort);
	}
	else
	{
		Socket socket = socketfactory.createSocket();
		SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
		SocketAddress remoteaddr = new InetSocketAddress(host, port);
		socket.bind(localaddr);
		socket.connect(remoteaddr, timeout);
		return socket;
	}
}
 
Example 2
Project: incubator-netbeans   File: DockerAction.java   Source Code and License Vote up 6 votes
private Endpoint createEndpoint() throws IOException {
    URL realUrl = getUrl();
    try {
        if ("https".equals(realUrl.getProtocol())) { // NOI18N
            SSLContext context = ContextProvider.getInstance().getSSLContext(instance);
            return Endpoint.forSocket(context.getSocketFactory().createSocket(realUrl.getHost(), realUrl.getPort()));
        } else if ("http".equals(realUrl.getProtocol())) { // NOI18N
            Socket s = new Socket(ProxySelector.getDefault().select(realUrl.toURI()).get(0));
            int port = realUrl.getPort();
            if (port < 0) {
                port = realUrl.getDefaultPort();
            }
            s.connect(new InetSocketAddress(realUrl.getHost(), port));
            return Endpoint.forSocket(s);
        } else {
            throw new IOException("Unknown protocol: " + realUrl.getProtocol());
        }
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }
}
 
Example 3
Project: Progetto-J   File: LoginFrame.java   Source Code and License Vote up 6 votes
/**
 * Lancia la connessione
 */
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
    if (!InetAddressValidator.getInstance().isValid(this.ipField.getText()) || Integer.parseInt(portField.getText()) > 65535)
        JOptionPane.showMessageDialog(this, "Indirizzo ip non valido", "Errore", JOptionPane.ERROR_MESSAGE);
    else {
        try {
            socket = new Socket();
            String ip = ipField.getText();
            int port = Integer.parseInt(portField.getText());
            socket.connect(new InetSocketAddress(ip, port), 10000);
            connectionLabel.setText("Connesso!");
            nickname = nicknameField.getText();
            //in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //out = new PrintStream(socket.getOutputStream(), true);
            Client client = new Client(socket, nickname);
            Thread clientThread = new Thread(client);
            clientThread.start();
            dispose();
        } catch (IOException ex) {
            connectionLabel.setText("Errore di connessione");
        }  
    }
}
 
Example 4
Project: crush   File: DRPMessenger.java   Source Code and License Vote up 6 votes
private synchronized void send(Message message) throws IOException {
	if(message == null) return;
			
	Socket socket = new Socket();
	socket.setReuseAddress(true);
	socket.setPerformancePreferences(2, 1, 0); // connection, latency, bandwidth
	socket.setTcpNoDelay(true);
	socket.setTrafficClass(0x10);	// low delay
	socket.setSoTimeout(timeoutMillis);
	socket.connect(address);
		
	@SuppressWarnings("resource")
       OutputStream out = socket.getOutputStream();
	
	// TODO additional check. Is it needed?
	if(out == null) throw new IOException("Socket has no output stream.");
	
	String text = message.toString();
	out.write(text.getBytes());
	
	if(CRUSH.debug) CRUSH.debug(this, "DRP> " + text);
	
	out.flush();
	socket.close();
}
 
Example 5
Project: JAVA-   File: TrackerGroup.java   Source Code and License Vote up 5 votes
/**
 * return connected tracker server
 *
 * @return connected tracker server, null for fail
 */
public TrackerServer getConnection(int serverIndex) throws IOException {
    Socket sock = new Socket();
    sock.setReuseAddress(true);
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(this.tracker_servers[serverIndex], ClientGlobal.g_connect_timeout);
    return new TrackerServer(sock, this.tracker_servers[serverIndex]);
}
 
Example 6
Project: mumu   File: ClientGlobal.java   Source Code and License Vote up 5 votes
/**
 * construct Socket object
 * @param ip_addr ip address or hostname
 * @param port port number
 * @return connected Socket object
 */
public static Socket getSocket(String ip_addr, int port) throws IOException {
    Socket sock = new Socket();
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(new InetSocketAddress(ip_addr, port), ClientGlobal.g_connect_timeout);
    return sock;
}
 
Example 7
Project: aos-FileCoreLibrary   File: DefaultSocketFactory.java   Source Code and License Vote up 5 votes
/***
 * Creates a Socket connected to the given host and port.
 * <p>
 * @param address The address of the host to connect to.
 * @param port The port to connect to.
 * @return A Socket connected to the given host and port.
 * @exception java.io.IOException If an I/O error occurs while creating the Socket.
 ***/
@Override
public Socket createSocket(InetAddress address, int port)
throws IOException
{
    if (connProxy != null)
    {
        Socket s = new Socket(connProxy);
        s.connect(new InetSocketAddress(address, port));
        return s;
    }
    return new Socket(address, port);
}
 
Example 8
Project: Pogamut3   File: SocketConnection.java   Source Code and License Vote up 5 votes
@Override
protected void unsyncConnect(ISocketConnectionAddress address) throws ConnectionException {
	log.info("Using encoding: " + encoding);
	socket = new Socket();
	try {
		socket.connect(new InetSocketAddress(address.getHost(), address.getPort()));
		socketReader = new InputStreamReader(socket.getInputStream(), encoding);
		socketWriter = new OutputStreamWriter(socket.getOutputStream(), encoding);
	} catch (IOException e) {
		throw new ConnectionException(e + " (" + address.getHost() + ":" + address.getPort() + ")", log);
	}
}
 
Example 9
Project: iBase4J   File: ClientGlobal.java   Source Code and License Vote up 5 votes
/**
 * construct Socket object
 *
 * @param addr InetSocketAddress object, including ip address and port
 * @return connected Socket object
 */
public static Socket getSocket(InetSocketAddress addr) throws IOException {
    Socket sock = new Socket();
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(addr, ClientGlobal.g_connect_timeout);
    return sock;
}
 
Example 10
Project: NoRiskNoFun   File: TCPServerSocketImplTests.java   Source Code and License Vote up 5 votes
void connect() {
    socket = new Socket();

    clientThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                socket.connect(new InetSocketAddress(HOST, PORT));
            } catch (IOException e) {
                exceptionInConnect = e;
            }
        }
    });
    clientThread.start();
}
 
Example 11
Project: nifi-tools   File: SocksProxySocketFactory.java   Source Code and License Vote up 5 votes
@Override
public Socket createSocket(String host, int port, InetAddress localHostAddr, int localPort) throws IOException, UnknownHostException {
    Socket socket = createSocket();
    socket.bind(new InetSocketAddress(localHostAddr, localPort));
    socket.connect(new InetSocketAddress(host, port));
    return socket;
}
 
Example 12
Project: hadoop-oss   File: StandardSocketFactory.java   Source Code and License Vote up 5 votes
@Override
public Socket createSocket(String host, int port) throws IOException,
    UnknownHostException {

  Socket socket = createSocket();
  socket.connect(new InetSocketAddress(host, port));
  return socket;
}
 
Example 13
Project: jdk8u-jdk   File: RedefineAgent.java   Source Code and License Vote up 5 votes
public static void agentmain(String args, Instrumentation inst) throws Exception {
    System.out.println("RedefineAgent running...");
    System.out.println("RedefineAgent redefine supported: " + inst.isRedefineClassesSupported());
    int port = Integer.parseInt(args);
    System.out.println("RedefineAgent connecting back to Tool....");
    Socket s = new Socket();
    s.connect( new InetSocketAddress(port) );
    System.out.println("RedefineAgent connected to Tool.");

    testRedefine(inst);

    s.close();
}
 
Example 14
Project: hadoop   File: TestBlockReplacement.java   Source Code and License Vote up 5 votes
private boolean replaceBlock(
    ExtendedBlock block,
    DatanodeInfo source,
    DatanodeInfo sourceProxy,
    DatanodeInfo destination,
    StorageType targetStorageType) throws IOException, SocketException {
  Socket sock = new Socket();
  try {
    sock.connect(NetUtils.createSocketAddr(destination.getXferAddr()),
        HdfsServerConstants.READ_TIMEOUT);
    sock.setKeepAlive(true);
    // sendRequest
    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    new Sender(out).replaceBlock(block, targetStorageType,
        BlockTokenSecretManager.DUMMY_TOKEN, source.getDatanodeUuid(),
        sourceProxy);
    out.flush();
    // receiveResponse
    DataInputStream reply = new DataInputStream(sock.getInputStream());

    BlockOpResponseProto proto =
        BlockOpResponseProto.parseDelimitedFrom(reply);
    while (proto.getStatus() == Status.IN_PROGRESS) {
      proto = BlockOpResponseProto.parseDelimitedFrom(reply);
    }
    return proto.getStatus() == Status.SUCCESS;
  } finally {
    sock.close();
  }
}
 
Example 15
Project: hadoop   File: SocksSocketFactory.java   Source Code and License Vote up 5 votes
@Override
public Socket createSocket(String host, int port,
    InetAddress localHostAddr, int localPort) throws IOException,
    UnknownHostException {

  Socket socket = createSocket();
  socket.bind(new InetSocketAddress(localHostAddr, localPort));
  socket.connect(new InetSocketAddress(host, port));
  return socket;
}
 
Example 16
Project: AirPlayAuth   File: AirPlayAuth.java   Source Code and License Vote up 5 votes
private Socket connect() throws IOException {
    Socket socket = new Socket();
    socket.setReuseAddress(true);
    socket.setSoTimeout(SOCKET_TIMEOUT);
    socket.connect(address, SOCKET_TIMEOUT);
    return socket;
}
 
Example 17
Project: GitHub   File: Platform.java   Source Code and License Vote up 4 votes
public void connectSocket(Socket socket, InetSocketAddress address,
    int connectTimeout) throws IOException {
  socket.connect(address, connectTimeout);
}
 
Example 18
Project: featurea   File: TcpMaster.java   Source Code and License Vote up 4 votes
private void openConnection() throws IOException {
    // Make sure any existing connection is closed.
    closeConnection();

    // Try 'retries' times to get the socket open.
    int retries = getRetries();
    int retryPause = RETRY_PAUSE_START;
    while (true) {
        try {
            socket = new Socket();
            socket.setSoTimeout(getTimeout());
            socket.connect(new InetSocketAddress(ipParameters.getHost(), ipParameters.getPort()), getTimeout());
            if (getePoll() != null) {
                transport = new EpollStreamTransport(socket.getInputStream(), socket.getOutputStream(), getePoll());
            } else {
                transport = new StreamTransport(socket.getInputStream(), socket.getOutputStream());
            }
            break;
        } catch (Throwable e) {
            closeConnection();
            if (retries <= 0) {
                throw new IOException(e);
            }
            retries--;
            try {
                Thread.sleep(retryPause);
            } catch (InterruptedException skip) {
                // no op
            }
            retryPause *= 2;
            if (retryPause > RETRY_PAUSE_MAX)
                retryPause = RETRY_PAUSE_MAX;
        }
    }

    BaseMessageParser ipMessageParser;
    WaitingRoomKeyFactory waitingRoomKeyFactory;
    if (ipParameters.isEncapsulated()) {
        ipMessageParser = new EncapMessageParser(true);
        waitingRoomKeyFactory = new EncapWaitingRoomKeyFactory();
    } else {
        ipMessageParser = new XaMessageParser(true);
        waitingRoomKeyFactory = new XaWaitingRoomKeyFactory();
    }

    conn = newMessageControl();
    conn.start(transport, ipMessageParser, null, waitingRoomKeyFactory);
    if (transport instanceof StreamTransport) {
        StreamTransport streamTransport = (StreamTransport) transport;
        streamTransport.start("Modbus4J TcpMaster");
    }
}
 
Example 19
Project: Alpsrln_Psc   File: main.java   Source Code and License Vote up 3 votes
public void run() {
	
	for (int port = 100; port < 150; port++) {

	try {
		
		Socket socket = new Socket();
		socket.connect(new InetSocketAddress(host,port));
		System.out.println("|+| Port " + port +" is open");
	}catch (IOException e){}
	
	}
}
 
Example 20
Project: Mafia   File: GameClient.java   Source Code and License Vote up 3 votes
@Override
public void run() {
	try {
		socket = new Socket();
		socket.connect(new InetSocketAddress(ip, port), CONNECT_TIMEOUT_SECONDS * 1000);
		
		in = new DataInputStream(socket.getInputStream());
		out = new DataOutputStream(socket.getOutputStream());
		
		
		out.writeUTF(Game.VERSION);	
		playerProfile.writePacket(out);
		
		initialPlayerCount = in.readInt();
		
		
		hasReceivedBaseData = true;
		
		
		while(true) {
			byte packetID = Packet.readID(in);
			Packet packet = Packet.readPacketByID(in, packetID);
			
			receivedPackets.add(packet);
		}
		
	} catch (IOException e) {
		System.out.println("Exception in client thread. Closing client.");
		
		wasExceptionCaught = true;
		closeClient();
	}
}