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

The following examples show how to use java.net.Socket#connect() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: RDFS   File: TestBlockReplacement.java    License: Apache License 2.0 6 votes vote down vote up
private boolean replaceBlock( Block block, DatanodeInfo source,
    DatanodeInfo sourceProxy, DatanodeInfo destination, int namespaceId) throws IOException {
  Socket sock = new Socket();
  sock.connect(NetUtils.createSocketAddr(
      destination.getName()), HdfsConstants.READ_TIMEOUT);
  sock.setKeepAlive(true);
  // sendRequest
  DataOutputStream out = new DataOutputStream(sock.getOutputStream());
  out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION);
  out.writeByte(DataTransferProtocol.OP_REPLACE_BLOCK);
  out.writeInt(namespaceId);
  out.writeLong(block.getBlockId());
  out.writeLong(block.getGenerationStamp());
  Text.writeString(out, source.getStorageID());
  sourceProxy.write(out);
  out.flush();
  // receiveResponse
  DataInputStream reply = new DataInputStream(sock.getInputStream());

  short status = reply.readShort();
  if(status == DataTransferProtocol.OP_STATUS_SUCCESS) {
    return true;
  }
  return false;
}
 
Example 2
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort,
                           final HttpConnectionParams params) throws IOException {
	if (params == null) {
		throw new IllegalArgumentException("Parameters may not be null");
	}
	int timeout = params.getConnectionTimeout();
	SocketFactory socketfactory = ctx.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 3
public void connect(int connectTimeout) {
    try {
        clientSocket = new Socket();

        clientSocket.connect(new InetSocketAddress(mllpHost, mllpPort), connectTimeout);

        clientSocket.setSoTimeout(soTimeout);
        clientSocket.setSoLinger(false, -1);
        clientSocket.setReuseAddress(reuseAddress);
        clientSocket.setTcpNoDelay(tcpNoDelay);

        inputStream = clientSocket.getInputStream();
        outputStream = new BufferedOutputStream(clientSocket.getOutputStream(), 2048);
    } catch (IOException e) {
        String errorMessage = String.format("Unable to establish connection to %s:%s", mllpHost, mllpPort);
        log.error(errorMessage, e);
        throw new MllpJUnitResourceException(errorMessage, e);
    }
}
 
Example 4
Source Project: big-c   File: SocksSocketFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Socket createSocket(InetAddress addr, int port,
    InetAddress localHostAddr, int localPort) throws IOException {

  Socket socket = createSocket();
  socket.bind(new InetSocketAddress(localHostAddr, localPort));
  socket.connect(new InetSocketAddress(addr, port));
  return socket;
}
 
Example 5
public static void main(String args[]) throws IOException {
    int port = Integer.parseInt(args[0]);

    System.out.println("Connecting to port " + port +
        " to shutdown Application ...");

    Socket s = new Socket();
    s.connect( new InetSocketAddress(port) );
    s.close();
}
 
Example 6
Source Project: RDFS   File: SocksSocketFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Socket createSocket(InetAddress addr, int port,
    InetAddress localHostAddr, int localPort) throws IOException {

  Socket socket = createSocket();
  socket.bind(new InetSocketAddress(localHostAddr, localPort));
  socket.connect(new InetSocketAddress(addr, port));
  return socket;
}
 
Example 7
Source Project: datakernel   File: AsyncHttpServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExpectContinue() throws Exception {
	Eventloop eventloop = Eventloop.create().withFatalErrorHandler(rethrowOnAnyError()).withCurrentThread();
	int port = getFreePort();
	AsyncHttpServer server = AsyncHttpServer.create(eventloop,
			request -> request.loadBody().map(body -> HttpResponse.ok200().withBody(body.slice())))
			.withListenPort(port);

	server.listen();
	Thread thread = new Thread(eventloop);
	thread.start();

	Socket socket = new Socket();
	socket.setTcpNoDelay(true);
	socket.connect(new InetSocketAddress("localhost", port));

	writeByRandomParts(socket, "POST /abc HTTP/1.0\r\nHost: localhost\r\nContent-Length: 5\r\nExpect: 100-continue\r\n\r\n");
	readAndAssert(socket.getInputStream(), "HTTP/1.1 100 Continue\r\n\r\n");

	writeByRandomParts(socket, "abcde");
	readAndAssert(socket.getInputStream(), "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 5\r\n\r\nabcde");

	assertEquals(0, toByteArray(socket.getInputStream()).length);
	assertTrue(socket.isClosed());
	socket.close();

	server.closeFuture().get();
	thread.join();
}
 
Example 8
Source Project: datakernel   File: AsyncHttpServerTest.java    License: Apache License 2.0 5 votes vote down vote up
private void doTestPipelining2(Eventloop eventloop, AsyncHttpServer server, int port) throws Exception {
	server.withListenPort(port);
	server.listen();
	Thread thread = new Thread(eventloop);
	thread.start();

	Socket socket = new Socket();
	socket.connect(new InetSocketAddress("localhost", port));

	for (int i = 0; i < 100; i++) {
		writeByRandomParts(socket, "GET /abc HTTP/1.0\r\nHost: localhost\r\n\r\n"
				+ "GET /123456 HTTP/1.1\r\nHost: localhost\r\n\r\n" +
				"POST /post1 HTTP/1.1\r\n" +
				"Host: localhost\r\n" +
				"Content-Length: 8\r\n" +
				"Content-Type: application/json\r\n\r\n" +
				"{\"at\":2}" +
				"POST /post2 HTTP/1.1\r\n" +
				"Host: localhost\r\n" +
				"Content-Length: 8\r\n" +
				"Content-Type: application/json\r\n\r\n" +
				"{\"at\":2}" +
				"");
	}

	for (int i = 0; i < 100; i++) {
		readAndAssert(socket.getInputStream(), "HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nContent-Length: 4\r\n\r\n/abc");
		readAndAssert(socket.getInputStream(), "HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nContent-Length: 7\r\n\r\n/123456");
		readAndAssert(socket.getInputStream(), "HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nContent-Length: 6\r\n\r\n/post1");
		readAndAssert(socket.getInputStream(), "HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nContent-Length: 6\r\n\r\n/post2");
	}

	server.closeFuture().get();
	thread.join();
}
 
Example 9
Source Project: msf4j   File: HostBindingTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check if a port is open with a given host. An SO timeout of 3000 milliseconds is used.
 * @param host The host to be checked.
 * @param port The port to be checked.
 * @return True if available, else false.
 */
private boolean isHostPortAvailable(String host, int port) {
    try {
        boolean isConnected;
        Socket client = new Socket();
        client.connect(new InetSocketAddress(host, port), 3000);
        isConnected = client.isConnected();
        client.close();
        return isConnected;
    } catch (IOException ignored) {
        return false;
    }
}
 
Example 10
public static void main(String args[]) throws Exception {

        if (args.length != 1) {
            throw new RuntimeException("Usage: ShutdownSimpleApplication" +
                " port-file");
        }

        // read the (TCP) port number from the given file

        File f = new File(args[0]);
        FileInputStream fis = new FileInputStream(f);
        byte b[] = new byte[8];
        int n = fis.read(b);
        if (n < 1) {
            throw new RuntimeException("Empty port-file");
        }
        fis.close();

        String str = new String(b, 0, n, "UTF-8");
        System.out.println("INFO: Port number of SimpleApplication: " + str);
        int port = Integer.parseInt(str);

        // Now connect to the port (which will shutdown application)

        System.out.println("INFO: Connecting to port " + port +
            " to shutdown SimpleApplication ...");
        System.out.flush();

        Socket s = new Socket();
        s.connect( new InetSocketAddress(port) );
        s.close();

        System.out.println("INFO: done connecting to SimpleApplication.");
        System.out.flush();

        System.exit(0);
    }
 
Example 11
Source Project: dremio-oss   File: BaseHttpsTestServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
  throws IOException, UnknownHostException {
  Socket socket = createSocket();
  socket.connect(new InetSocketAddress(host, port));
  return socket;
}
 
Example 12
public void testShutdownOutputWithoutOption(ServerBootstrap sb) throws Throwable {
    TestHandler h = new TestHandler();
    Socket s = new Socket();
    try {
        sb.childHandler(h).bind().sync();

        s.connect(addr, 10000);
        s.getOutputStream().write(1);

        assertEquals(1, (int) h.queue.take());

        assertTrue(h.ch.isOpen());
        assertTrue(h.ch.isActive());
        assertFalse(h.ch.isInputShutdown());
        assertFalse(h.ch.isOutputShutdown());

        s.shutdownOutput();

        h.closure.await();

        assertFalse(h.ch.isOpen());
        assertFalse(h.ch.isActive());
        assertTrue(h.ch.isInputShutdown());
        assertTrue(h.ch.isOutputShutdown());

        assertEquals(1, h.halfClosure.getCount());
        Thread.sleep(100);
        assertEquals(0, h.halfClosureCount.intValue());
    } finally {
        s.close();
    }
}
 
Example 13
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
Source Project: SPDS   File: SocketLongTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test4() throws IOException {
    Collection<Socket> sockets = createSockets();
    for (Iterator<Socket> it = sockets.iterator(); it.hasNext();) {
        Socket s = (Socket) it.next();
        s.connect(null);
        talk(s);
        mustBeInAcceptingState(s);
    }

    Collection<Socket> s1 = createOther();
}
 
Example 15
Source Project: CordovaYoutubeVideoPlayer   File: Platform.java    License: MIT License 5 votes vote down vote up
@Override public void connectSocket(Socket socket, InetSocketAddress address,
    int connectTimeout) throws IOException {
  try {
    socket.connect(address, connectTimeout);
  } catch (SecurityException se) {
    // Before android 4.3, socket.connect could throw a SecurityException
    // if opening a socket resulted in an EACCES error.
    IOException ioException = new IOException("Exception in connect");
    ioException.initCause(se);
    throw ioException;
  }
}
 
Example 16
public static void main(String[] args) throws Exception {
    String pid = args[0]; // pid as a string
    System.out.println("Starting TestManager for PID = " + pid);
    System.out.flush();
    VirtualMachine vm = VirtualMachine.attach(pid);

    String agentPropLocalConnectorAddress = (String)
        vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);

    int vmid = Integer.parseInt(pid);
    String jvmstatLocalConnectorAddress =
        ConnectorAddressLink.importFrom(vmid);

    if (agentPropLocalConnectorAddress == null &&
        jvmstatLocalConnectorAddress == null) {
        // No JMX Connector address so attach to VM, and start local agent
        startManagementAgent(pid);
        agentPropLocalConnectorAddress = (String)
            vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);
        jvmstatLocalConnectorAddress =
            ConnectorAddressLink.importFrom(vmid);
    }


    // Test address obtained from agent properties
    System.out.println("Testing the connector address from agent properties");
    connect(pid, agentPropLocalConnectorAddress);

    // Test address obtained from jvmstat buffer
    System.out.println("Testing the connector address from jvmstat buffer");
    connect(pid, jvmstatLocalConnectorAddress);

    // Shutdown application
    int port = Integer.parseInt(args[1]);
    System.out.println("Shutdown process via TCP port: " + port);
    Socket s = new Socket();
    s.connect(new InetSocketAddress(port));
    s.close();
}
 
Example 17
public static void main(String args[]) throws IOException {
    int port = Integer.parseInt(args[0]);

    System.out.println("Connecting to port " + port +
        " to shutdown Application ...");

    Socket s = new Socket();
    s.connect( new InetSocketAddress(port) );
    s.close();
}
 
Example 18
Source Project: big-c   File: TestBlockReplacement.java    License: Apache License 2.0 5 votes vote down vote up
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 19
@Override
public Socket createSocket(final InetAddress host, final int port) throws IOException {
    final Socket socket = createSocket();
    socket.connect(new InetSocketAddress(host, port));
    return socket;
}
 
Example 20
static void connectWithTimeout(Socket socket) throws IOException {
    socket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 1234), 500);
}