Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

In this page you can find the example usage for java.net Socket Socket.

Prototype

public Socket(InetAddress address, int port) throws IOException 

Source Link

Document

Creates a stream socket and connects it to the specified port number at the specified IP address.

Usage

From source file:com.willwinder.universalgcodesender.connection.TCPConnection.java

@Override
public boolean openPort() throws Exception {
    responseMessageHandler = new ResponseMessageHandler();

    try {/*  w  w w .  ja  va2s  .  c o m*/
        client = new Socket(host, port);
    } catch (BindException e) {
        throw new ConnectionException("Could not bind a local port.", e);
    } catch (NoRouteToHostException e) {
        throw new ConnectionException(
                "No route to host. The remote host may not be running, blocked by a firewall, or disconnected.",
                e);
    } catch (ConnectException e) {
        throw new ConnectionException(
                "The port is unreachable on the remote host. The server may not be running, or blocked by a firewall.",
                e);
    }

    if (client == null) {
        throw new ConnectionException("Socket unable to connect.");
    }

    bufOut = client.getOutputStream();
    inStream = new InputStreamReader(client.getInputStream());
    bufIn = new BufferedReader(inStream);

    // start thread so replies can be handled
    replyThread = new Thread(this);
    replyThread.start();

    return client.isConnected();
}

From source file:fr.norad.jmxzabbix.core.ZabbixClient.java

public void send(EvictingQueue<ZabbixRequest> dataQueue) throws IOException {
    if (dataQueue.isEmpty()) {
        return;//w  w  w.j a v a2s  .  com
    }
    try (Socket zabbix = new Socket(config.getHost(), config.getPort());
            OutputStream out = zabbix.getOutputStream();
            InputStream in = zabbix.getInputStream()) {

        zabbix.setSoTimeout(config.getTimeoutSecond() * 1000);

        ZabbixRequest current = null;
        while (!dataQueue.isEmpty()) {
            try {
                current = dataQueue.poll();
                LOGGER.debug("sending request" + current);
                asClientWriteRequest(out, current);
                out.flush();
                LOGGER.debug("request sent");
                LOGGER.debug("reading response");
                ZabbixResponse zabbixResponse = asClientReadResponse(in);
                LOGGER.debug("response read" + zabbixResponse);
            } catch (Exception e) {
                if (current != null) {
                    dataQueue.add(current);
                }
                throw new IllegalStateException("Communication with Zabbix goes wrong", e);
            }
        }
    } catch (ConnectException e) {
        throw new IOException("Cannot connect to " + config.getHost() + ':' + config.getPort());
    }
}

From source file:com.linecorp.armeria.internal.ConnectionLimitingHandlerIntegrationTest.java

private Socket newSocketAndTest() throws IOException {
    Socket socket = new Socket(LOOPBACK, server.httpPort());

    // Test this socket is opened or not.
    OutputStream os = socket.getOutputStream();
    os.write("GET / HTTP/1.1\r\n\r\n".getBytes());
    os.flush();//from  ww w . ja v a 2  s . co m

    // Read the next byte and ignore it.
    socket.getInputStream().read();

    return socket;
}

From source file:com.chigix.bio.proxy.buffer.FixedBufferTest.java

License:asdf

@Test
public void testHTTPS() {
    System.out.println("BANKAI");
    Socket tmp_socket = null;//from  ww  w. ja va  2s .co  m
    try {
        tmp_socket = new Socket("jp.jfwq.net", 6002);
    } catch (IOException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    final Socket socket = tmp_socket;
    new Thread() {

        @Override
        public void run() {
            while (true) {
                try {
                    int read;
                    System.out.print(read = socket.getInputStream().read());
                    System.out.print((char) read);
                    System.out.print(",");
                } catch (IOException ex) {
                    Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }.start();
    try {
        socket.getOutputStream()
                .write("CONNECT www.dnspod.cn:443 HTTP/1.1\nHost: www.dnspod.cn:443\n\n".getBytes());
    } catch (IOException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        Thread.sleep(50000);
    } catch (InterruptedException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.mybox.mybox.ClientSetup.java

/**
 * Get the initial input from the user/*from   w w  w  .jav a2  s  .c o m*/
 */
private void gatherInput() {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String input = null;

    System.out.print("Configuration directory [" + configDir + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }
    if (!input.isEmpty())
        configDir = input;

    System.out.print("Data directory [" + account.directory + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }
    if (!input.isEmpty())
        account.directory = input;

    System.out.print("Server name [" + account.serverName + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }
    if (!input.isEmpty())
        account.serverName = input;

    System.out.print("Server port [" + account.serverPort + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }

    if (!input.isEmpty()) {
        account.serverPort = Integer.parseInt(input); //catch
    }

    Socket socket = null;
    try {
        socket = new Socket(account.serverName, account.serverPort);
    } catch (IOException e) {
        Client.printErrorExit("Unable to contact server");
    }

    System.out.print("Email [" + account.email + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }
    if (!input.isEmpty())
        account.email = input;

    Console console = System.console();

    if (console != null)
        input = new String(console.readPassword("Password [" + password + "]: "));
    else
        System.err.println("Unable to get password since not in console");

    //System.out.println("pw input : " + input);

    if (!input.isEmpty())
        password = input;
}

From source file:com.metaparadigm.dict.DictClient.java

private synchronized void connect() throws IOException, DictClientException {
    System.out.println("DictClient.connect: opening connection to " + host + ":" + port);
    sock = new Socket(host, port);
    in = new BufferedReader(new InputStreamReader(sock.getInputStream(), CharEncoding.UTF_8));
    out = new PrintWriter(new OutputStreamWriter(sock.getOutputStream(), CharEncoding.UTF_8));
    DictCommandResult r = new DictCommandResult(in.readLine());
    if (r.code != DictCommandResult.BANNER) {
        close();//from  w  w  w .  ja  va 2  s .  co m
        throw new DictClientException(r);
    }
    ident = r.msg;
    System.out.println("DictClient.connect: connected to " + host + ":" + port + " ident=\"" + ident + "\"");
}

From source file:org.mule.module.http.functional.listener.HttpListenerPersistentConnectionsTestCase.java

protected void assertConnectionClosesAfterTimeout(DynamicPort port, HttpVersion httpVersion)
        throws IOException, InterruptedException {
    Socket socket = new Socket("localhost", port.getNumber());
    sendRequest(socket, httpVersion);/*from   w  ww .j  a  v  a  2  s. c  o m*/
    assertResponse(getResponse(socket), true);

    sendRequest(socket, httpVersion);
    assertResponse(getResponse(socket), true);

    Thread.sleep(3000);

    sendRequest(socket, httpVersion);
    assertResponse(getResponse(socket), false);

    socket.close();
}

From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManagerTest.java

@Test
public void testChooseClientAliasStartcom() throws Exception {
    final AtomicBoolean choose = new AtomicBoolean();
    final X509KeyManager m = new CertificateStoreX509KeyManager(new DisabledCertificateStore() {
        @Override//from w  w w .  j  ava 2  s.c om
        public X509Certificate choose(String[] keyTypes, Principal[] issuers, String hostname, String prompt)
                throws ConnectionCanceledException {
            assertEquals(
                    "The server requires a certificate to validate your identity. Select the certificate to authenticate yourself to test.cyberduck.ch.",
                    prompt);
            for (Principal issuer : issuers) {
                assertEquals("CN=StartCom Class 2 Primary Intermediate Client CA", issuer.getName());
            }
            choose.set(true);
            throw new ConnectionCanceledException();
        }
    }).init();
    assertNull(m.chooseClientAlias(new String[] { "RSA", "DSA" },
            new Principal[] { new X500Principal("CN=StartCom Class 2 Primary Intermediate Client CA") },
            new Socket("test.cyberduck.ch", 443)));
    assertTrue(choose.get());
}

From source file:WriteDoubleUsingSockets.java

public void init() {
    Date d = new Date();
    // Get the portnumber and servername and allow to be called from a
    // java main program also
    try {/*from  w  w w  . j a v  a  2 s . co  m*/
        String param;
        param = getParameter("PortNumber");
        if (param != null)
            PortNumber = Integer.parseInt(param);
        param = getParameter("ServerName");
        if (param != null)
            ServerName = param;
    } catch (NullPointerException e) { // Must be called from a main ignore
    }
    try {
        Socket skt = new Socket(ServerName, PortNumber);
        os = new DataOutputStream(skt.getOutputStream());
    } catch (Exception e) {
        Label l = new Label(e.toString());
        add(l);
        System.out.println(e);
        return;
    }
    try {
        s = new ObjectOutputStream(os);
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Unable to open stream as an object stream");
    }
    try {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 25; i++) {
            s.writeObject(new Double(i));
        }
        os.close();
        long endTime = System.currentTimeMillis() - startTime;
        Label l = new Label(
                "Writing 25 doubles server took: " + new Long(endTime).toString() + " milliseconds.");
        add(l);
        System.out.println("Object written");
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Unable to write Objects");
    }
}

From source file:com.googlecode.icegem.cacheutils.common.Utils.java

/**
 * Checks if the socket of specified host and port is alive.
 * //from   w w  w.  j a  v  a 2  s . c  o  m
 * @param host
 *            - the host.
 * @param port
 *            - the port.
 * @return - true if alive, false otherwise.
 */
public static boolean isSocketAlive(String host, int port) {
    boolean socketAlive = false;
    Socket socket = null;

    try {
        socket = new Socket(host, port);

        socketAlive = socket.isConnected();
    } catch (Throwable t) {
        // do nothing
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                // do nothing
            }
        }
    }

    return socketAlive;
}