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:monasca.api.integration.docker.ITInfluxDBTest.java

boolean isPortFree(int port) {

    try (Socket s = new Socket("localhost", port)) {
        return false;
    } catch (Exception e) {
        return true;
    }//from w  ww  . j a  v  a  2 s  . c  o m

}

From source file:com.esofthead.mycollab.jetty.GenericServerRunner.java

/**
 * Run web server with arguments//from   w  w w  .  j a  v  a 2s . com
 *
 * @param args
 * @throws Exception
 */
void run(String[] args) throws Exception {
    ServerInstance.getInstance().registerInstance(this);
    System.setProperty("org.eclipse.jetty.annotations.maxWait", "180");
    int stopPort = 0;
    String stopKey = null;
    boolean isStop = false;

    for (int i = 0; i < args.length; i++) {
        if ("--stop-port".equals(args[i])) {
            stopPort = Integer.parseInt(args[++i]);
        } else if ("--stop-key".equals(args[i])) {
            stopKey = args[++i];
        } else if ("--stop".equals(args[i])) {
            isStop = true;
        } else if ("--port".equals(args[i])) {
            port = Integer.parseInt(args[++i]);
        }
    }

    switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
    case 1:
        usage("Must specify --stop-key when --stop-port is specified");
        break;

    case 2:
        usage("Must specify --stop-port when --stop-key is specified");
        break;

    case 3:
        if (isStop) {
            try (Socket s = new Socket(InetAddress.getByName("localhost"), stopPort);
                    OutputStream out = s.getOutputStream()) {
                out.write((stopKey + "\r\nstop\r\n").getBytes());
                out.flush();
            }
            return;
        } else {
            ShutdownMonitor monitor = ShutdownMonitor.getInstance();
            monitor.setPort(stopPort);
            monitor.setKey(stopKey);
            monitor.setExitVm(true);
            break;
        }
    }

    execute();
}

From source file:ClientManager.java

private void connectController() throws UnknownHostException, IOException {
    sock = new Socket(controller, controller_port);
    os = new DataOutputStream(sock.getOutputStream());
    is = new BufferedReader(new InputStreamReader(sock.getInputStream()));

    JSONObject jo = new JSONObject();
    jo.put("Type", "Announce");
    jo.put("DPID", dpid);
    jo.put("IP", ip.getHostAddress());

    send(jo);//from w  w  w. ja  v a 2 s .  com
    out.println("Sent " + jo);
}

From source file:barrysw19.calculon.icc.ICCInterface.java

public void connect() throws IOException {
    connection = new Socket("chessclub.com", 23);
    doLogin();/*from   w w w.  ja va  2 s .  c o m*/
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    out = new PrintStream(connection.getOutputStream());

    send("set level1 1");
    send("set style 12");
    if (!StringUtils.isBlank(iccConfig.getFormula())) {
        send("set formula " + iccConfig.getFormula());
    }
    receiveLevel2(DgCommand.DG_MY_GAME_STARTED, DgCommand.DG_MY_GAME_RESULT, DgCommand.DG_SEND_MOVES,
            DgCommand.DG_MOVE_ALGEBRAIC, DgCommand.DG_MOVE_SMITH, DgCommand.DG_MOVE_TIME,
            DgCommand.DG_MOVE_CLOCK, DgCommand.DG_MSEC);

    setStatus();
    if (iccConfig.isReseek()) {
        reseek();
    }

    Runnable keepAlive = () -> {
        while (alive) {
            send("games *r-e-B-o-M-f-K-w-L-d-z");
            try {
                Thread.sleep(60000);
            } catch (InterruptedException x) {
                // Ignore
            }
        }
    };
    Thread keepAliveThread = new Thread(keepAlive);
    keepAliveThread.setDaemon(true);
    keepAliveThread.start();

    StringBuilder line = new StringBuilder();
    int c;
    try {
        while ((c = reader.read()) != -1) {
            lv1BlockHandler.add((char) c);

            // Ignore CTRL-M, CTRL-G
            if (c == ('M' & 0x1F) || c == ('G' & 0x1F)) {
                continue;
            }
            line.append((char) c);
            if (c == '\n') {
                fireDataReceived(line.toString());
                line.setLength(0);
                continue;
            }
            if (line.length() >= 2 && line.charAt(line.length() - 2) == ('Y' & 0x1F)
                    && line.charAt(line.length() - 1) == ']') {
                fireDataReceived(line.toString());
                line.setLength(0);
            }
        }
    } finally {
        alive = false;
        try {
            reader.close();
            out.close();
        } catch (Exception x) {
            // ignore
        }
    }
}

From source file:com.impetus.client.persistence.CassandraCli.java

/**
 * Check if server running.//from  ww  w .  j  a  v  a 2s . c o m
 * 
 * @return true, if successful
 */
private static boolean checkIfServerRunning() {
    try {
        Socket socket = new Socket("127.0.0.1", 9160);
        return socket.getInetAddress() != null;
    } catch (UnknownHostException e) {
        return false;
    } catch (IOException e) {
        return false;
    }

}

From source file:com.qmetry.qaf.automation.ui.UiDriverFactory.java

private static boolean isSeverRunning(String host, int port) {
    boolean isRunning = false;

    Socket socket = null;/*from   www.  j  av  a  2s  .  c o m*/
    try {
        socket = new Socket(host, (port));
        isRunning = socket.isConnected();
    } catch (Exception exp) {
        logger.error("Error occured while checking Selenium : " + exp.getMessage());
    } finally {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {

        }
    }
    return isRunning;
}

From source file:com.android.unit_tests.TestHttpService.java

/**
 * This test case executes a series of simple GET requests 
 *//* www. j a v  a 2 s . c  o m*/
@LargeTest
public void testSimpleBasicHttpRequests() throws Exception {

    int reqNo = 20;

    Random rnd = new Random();

    // Prepare some random data
    final List testData = new ArrayList(reqNo);
    for (int i = 0; i < reqNo; i++) {
        int size = rnd.nextInt(5000);
        byte[] data = new byte[size];
        rnd.nextBytes(data);
        testData.add(data);
    }

    // Initialize the server-side request handler
    this.server.registerHandler("*", new HttpRequestHandler() {

        public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {

            String s = request.getRequestLine().getUri();
            if (s.startsWith("/?")) {
                s = s.substring(2);
            }
            int index = Integer.parseInt(s);
            byte[] data = (byte[]) testData.get(index);
            ByteArrayEntity entity = new ByteArrayEntity(data);
            response.setEntity(entity);
        }

    });

    this.server.start();

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    HttpHost host = new HttpHost("localhost", this.server.getPort());

    try {
        for (int r = 0; r < reqNo; r++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, this.client.getParams());
            }

            BasicHttpRequest get = new BasicHttpRequest("GET", "/?" + r);
            HttpResponse response = this.client.execute(get, host, conn);
            byte[] received = EntityUtils.toByteArray(response.getEntity());
            byte[] expected = (byte[]) testData.get(r);

            assertEquals(expected.length, received.length);
            for (int i = 0; i < expected.length; i++) {
                assertEquals(expected[i], received[i]);
            }
            if (!this.client.keepAlive(response)) {
                conn.close();
            }
        }

        //Verify the connection metrics
        HttpConnectionMetrics cm = conn.getMetrics();
        assertEquals(reqNo, cm.getRequestCount());
        assertEquals(reqNo, cm.getResponseCount());

    } finally {
        conn.close();
        this.server.shutdown();
    }
}

From source file:net.ab0oo.aprs.avrs.AVRSServer.java

private void connectAndListen() {
    String sentence;/*  w ww  .  jav  a  2  s .  c o  m*/
    String modifiedSentence = "";
    try {
        clientSocket = new Socket(aprsIsServer, port);
        outToServer = new DataOutputStream(clientSocket.getOutputStream());
        inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        // sentence = "user ab0oo-15 pass 19951 vers test 1.0 filter a/35.000/-85.6/30.3555/-80.84";
        sentence = "user " + callsign + " pass " + aprsPass + " vers test 1.0 filter t/mp";
        outToServer.writeBytes(sentence + '\n');
    } catch (Exception ex) {
        System.err.println("Unable to contact/log-in to APRS-IS:  " + ex);
        System.exit(1);
    }
    APRSPacket packet = null;
    while (true) {
        try {
            modifiedSentence = inFromServer.readLine();
            if (modifiedSentence.length() > 1 && modifiedSentence.charAt(0) != '#') {
                try {
                    packet = Parser.parse(modifiedSentence);
                } catch (Exception ex) {
                    System.err.println("Unable to parse: " + modifiedSentence);
                    ex.printStackTrace();
                    continue;
                }
                if (packet.hasFault()) {
                    System.err.println("Bad Packet");
                    continue;
                }
                processPacket(packet);
            } else {
                System.out.println(modifiedSentence);
            }
            System.out.println(new Date() + ":  " + modifiedSentence);

        } catch (Exception ex) {
            System.err.println("Exception during Network read:  " + ex);
            ex.printStackTrace();
            System.err.println("Culprit was " + modifiedSentence);
        }
    }
    // clientSocket.close();
}

From source file:bigbird.benchmark.BenchmarkWorker.java

public void run() {

    HttpResponse response = null;/*from w  w  w .  j a va 2s .c  o m*/
    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

    String hostname = targetHost.getHostName();
    int port = targetHost.getPort();
    if (port == -1) {
        port = 80;
    }

    // Populate the execution context
    this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
    //        this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);

    stats.start();
    for (int i = 0; i < count; i++) {

        try {
            HttpRequest req = requestGenerator.generateRequest(count);

            if (!conn.isOpen()) {
                Socket socket = null;
                if ("https".equals(targetHost.getSchemeName())) {
                    SocketFactory socketFactory = SSLSocketFactory.getDefault();
                    socket = socketFactory.createSocket(hostname, port);
                } else {
                    socket = new Socket(hostname, port);
                }
                conn.bind(socket, params);
            }

            try {
                // Prepare request
                this.httpexecutor.preProcess(req, this.httpProcessor, this.context);
                // Execute request and get a response
                response = this.httpexecutor.execute(req, conn, this.context);
                // Finalize response
                this.httpexecutor.postProcess(response, this.httpProcessor, this.context);

            } catch (HttpException e) {
                stats.incWriteErrors();
                if (this.verbosity >= 2) {
                    System.err.println("Failed HTTP request : " + e.getMessage());
                }
                continue;
            }

            verboseOutput(req, response);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                stats.incSuccessCount();
            } else {
                stats.incFailureCount();
                continue;
            }

            HttpEntity entity = response.getEntity();
            String charset = EntityUtils.getContentCharSet(entity);
            if (charset == null) {
                charset = HTTP.DEFAULT_CONTENT_CHARSET;
            }
            long contentlen = 0;
            if (entity != null) {
                InputStream instream = entity.getContent();
                int l = 0;
                while ((l = instream.read(this.buffer)) != -1) {
                    stats.incTotalBytesRecv(l);
                    contentlen += l;
                    if (this.verbosity >= 4) {
                        String s = new String(this.buffer, 0, l, charset);
                        System.out.print(s);
                    }
                }
                instream.close();
            }

            if (this.verbosity >= 4) {
                System.out.println();
                System.out.println();
            }

            if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
                conn.close();
            }
            stats.setContentLength(contentlen);

        } catch (IOException ex) {
            ex.printStackTrace();
            stats.incFailureCount();
            if (this.verbosity >= 2) {
                System.err.println("I/O error: " + ex.getMessage());
            }
        }

    }
    stats.finish();

    if (response != null) {
        Header header = response.getFirstHeader("Server");
        if (header != null) {
            stats.setServerName(header.getValue());
        }
    }

    try {
        conn.close();
    } catch (IOException ex) {
        ex.printStackTrace();
        stats.incFailureCount();
        if (this.verbosity >= 2) {
            System.err.println("I/O error: " + ex.getMessage());
        }
    }
}

From source file:InterruptibleSocketTest.java

/**
 * Connects to the test server, using blocking I/O
 *//*w w  w. j a va  2  s  .  co  m*/
public void connectBlocking() throws IOException {
    messages.append("Blocking:\n");
    Socket sock = new Socket("localhost", 8189);
    try {
        in = new Scanner(sock.getInputStream());
        while (!Thread.currentThread().isInterrupted()) {
            messages.append("Reading ");
            if (in.hasNextLine()) {
                String line = in.nextLine();
                messages.append(line);
                messages.append("\n");
            }
        }
    } finally {
        sock.close();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                messages.append("Socket closed\n");
                interruptibleButton.setEnabled(true);
                blockingButton.setEnabled(true);
            }
        });
    }
}