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.codefollower.lealone.omid.TestUtils.java

public static void waitForSocketNotListening(String host, int port, int sleepTimeMillis)
        throws UnknownHostException, IOException, InterruptedException {
    while (true) {
        Socket sock = null;//from   w w  w . j a  v  a2 s.c  o  m
        try {
            sock = new Socket(host, port);
        } catch (IOException e) {
            // ignore as this is expected
            break;
        } finally {
            if (sock != null) {
                sock.close();
            }
        }
        Thread.sleep(sleepTimeMillis);
        LOG.info("Host " + host + ":" + port + " is up");
    }
}

From source file:Main.java

public InputStream getWWWPageStream(String host, String file) throws IOException, UnknownHostException {

    InetAddress webServer = InetAddress.getByName(host);

    Socket httpPipe = new Socket(webServer, 80);
    if (httpPipe == null) {
        System.out.println("Socket to Web server creation failed.");
        return null;
    }/*from  w w  w . j  av a2 s .c  o m*/

    InputStream inn = httpPipe.getInputStream(); // get raw streams
    OutputStream outt = httpPipe.getOutputStream();

    DataInputStream in = new DataInputStream(inn); // turn into higher-level ones
    PrintStream out = new PrintStream(outt);

    if (inn == null || outt == null) {
        System.out.println("Failed to open streams to socket.");
        return null;
    }
    out.println("GET " + file + " HTTP/1.0\n");

    String response;
    while ((response = in.readUTF()).length() > 0) {
        System.out.println(response);
    }

    return in;
}

From source file:Main.java

/**
 * Sends Gps data to emulator, and the start value has an offset.
 * //from   ww  w  .  j  av  a 2s . c om
 * @param number send times
 * @param offset is used to compute the start latitude and longitude
 * @param pause pause interval between each sending
 */
public static void sendGps(int number, int offset, int pause) {
    if (number < 1) {
        return;
    }

    int pauseInterval = TINY_WAIT_TIME;
    if (pause != -1) {
        pauseInterval = pause;
    }

    // If it's a real device, does not send simulated GPS signal.
    if (!isEmulator) {
        return;
    }

    PrintStream out = null;
    Socket socket = null;
    try {
        socket = new Socket(ANDROID_LOCAL_IP, emulatorPort);
        out = new PrintStream(socket.getOutputStream());
        double longitude = START_LONGITUDE + offset * DELTA_LONGITUDE;
        double latitude = START_LATITUDE + offset * DELTA_LADITUDE;
        for (int i = 0; i < number; i++) {
            out.println("geo fix " + longitude + " " + latitude);
            longitude += DELTA_LONGITUDE;
            latitude += DELTA_LADITUDE;
            Thread.sleep(pauseInterval);
        }
        // Wait the GPS signal can be obtained by MyTracks.
        Thread.sleep(SHORT_WAIT_TIME);
    } catch (UnknownHostException e) {
        System.exit(-1);
    } catch (IOException e) {
        System.exit(-1);
    } catch (InterruptedException e) {
        System.exit(-1);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.sharneng.net.portforward.TargetConnector.java

public Socket openSocket() throws java.io.IOException {
    return new Socket(to.getAddress(), to.getPort());
}

From source file:actuatorapp.ActuatorApp.java

public ActuatorApp() throws IOException, JSONException {
    //Takes a sting with a relay name "RELAYLO1-10FAD.relay1"
    //Actuator a = new Actuator("RELAYLO1-12854.relay1");    
    //Starts the virtualhub that is needed to connect to the actuators
    Process process = new ProcessBuilder("src\\actuatorapp\\VirtualHub.exe").start();
    //{"yocto_addr":"10FAD","payload":{"value":true},"type":"control"}

    api = new Socket("10.42.72.25", 8082);
    OutputStreamWriter osw = new OutputStreamWriter(api.getOutputStream(), StandardCharsets.UTF_8);
    InputStreamReader isr = new InputStreamReader(api.getInputStream(), StandardCharsets.UTF_8);

    //Sends JSON authentication to CommandAPI
    JSONObject secret = new JSONObject();
    secret.put("type", "authenticate");
    secret.put("secret", "testpass");
    osw.write(secret.toString() + "\r\n");
    osw.flush();//from  www .  j a  v  a 2  s  . c om
    System.out.println("sent");

    //Waits and recieves JSON authentication response
    BufferedReader br = new BufferedReader(isr);
    JSONObject response = new JSONObject(br.readLine());
    System.out.println(response.toString());
    if (!response.getBoolean("success")) {
        System.err.println("Invalid API secret");
        System.exit(1);
    }

    try {
        while (true) {
            //JSON object will contain message from the server
            JSONObject type = getCommand(br);
            //Forward the command to be processed (will find out which actuators to turn on/off)
            commandFromApi(type);
        }
    } catch (Exception e) {
        System.out.println("Error listening to api");
    }

}

From source file:com.splout.db.benchmark.TCPTest.java

public static void tcpTest(String file, String table)
        throws UnknownHostException, IOException, InterruptedException, JSONSerDeException {
    final TCPServer server = new TCPServer(8888, file, table);

    Thread t = new Thread() {
        @Override//  w w w.j a  v  a  2  s.com
        public void run() {
            server.serve();
        }
    };
    t.start();

    while (!server.isServing()) {
        Thread.sleep(100);
    }

    Socket clientSocket = new Socket("localhost", 8888);
    DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));

    try {
        do {
            // Read a record
            inFromServer.readUTF();
            inFromServer.readInt();
            inFromServer.readDouble();
            inFromServer.readUTF();
        } while (true);
    } catch (Throwable th) {
        th.printStackTrace();
    }

    clientSocket.close();
    server.stop();
    t.interrupt();
}

From source file:TcpClient.java

/** Default constructor. */
public TcpClient()
{
    try/*from  ww w .j  a  v a  2  s.  c  o  m*/
    {
        this.socket = new Socket(SERVER_HOSTNAME, COMM_PORT);
        InputStream iStream = this.socket.getInputStream();
        ObjectInputStream oiStream = new ObjectInputStream(iStream);
        this.payload = (TcpPayload) oiStream.readObject();
    }
    catch (UnknownHostException uhe)
    {
        System.out.println("Don't know about host: " + SERVER_HOSTNAME);
        System.exit(1);
    }
    catch (IOException ioe)
    {
        System.out.println("Couldn't get I/O for the connection to: " +
            SERVER_HOSTNAME + ":" + COMM_PORT);
        System.exit(1);
    }
    catch(ClassNotFoundException cne)
    {
        System.out.println("Wanted class TcpPayload, but got class " + cne);
    }
    System.out.println("Received payload:");
    System.out.println(this.payload.toString());
}

From source file:org.openbaton.autoscaling.utils.Utils.java

public static boolean available(String ip, String port) {
    try {/*from   www . j a va  2 s. c  om*/
        Socket s = new Socket(ip, Integer.parseInt(port));
        log.info("NFVO is listening on port " + port + " at " + ip);
        s.close();
        return true;
    } catch (IOException ex) {
        // The remote host is not listening on this port
        log.warn("NFVO is not reachable on port " + port + " at " + ip);
        return false;
    }
}

From source file:gomoku.aneh.MainForm.java

/**
 * Creates new form main//ww w  .ja v a2  s .c  o m
 */
public MainForm() {

    try {
        socket = new Socket("127.0.0.1", 8080);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = socket.getInputStream();

    } catch (UnknownHostException e) {
        System.out.println("Unknown host");
        System.exit(1);
    } catch (IOException e) {
        System.out.println("No I/O");
        System.exit(1);
    }

    new Thread(new listenner(this));

    out.print("GET /\nSec-WebSocket-Key: abcdefghij\n\n");
    out.flush();

    initComponents();

    setLayout(new BorderLayout());
    panel = new JPanel();
    panel.setLayout(null);
    add(panel);
    boardButton = new JButton[20][20];
    for (int i = 0; i < 20; i++)
        for (int j = 0; j < 20; j++) {
            boardButton[i][j] = new JButton("");
            boardButton[i][j].setBounds(i * 20 + 10, j * 20 + 70, 20, 20);
            panel.add(boardButton[i][j]);
        }
}

From source file:Main.java

/**
 * Sends Gps data to emulator, and the start value has an offset.
 * /*from ww  w  . j a v  a 2 s .  c  o m*/
 * @param number send times
 * @param offset is used to compute the start latitude and longitude 
 * @param pause pause interval between each sending
 */
public static void sendGps(int number, int offset, int pause) {
    if (number < 1) {
        return;
    }

    int pauseInterval = PAUSE_DEFAULT;
    if (pause != -1) {
        pauseInterval = pause;
    }

    // If it's a real device, does not send simulated GPS signal.
    if (!isEmulator) {
        return;
    }

    PrintStream out = null;
    Socket socket = null;
    try {
        socket = new Socket(ANDROID_LOCAL_IP, emulatorPort);
        out = new PrintStream(socket.getOutputStream());
        double longitude = START_LONGITUDE + offset * DELTA_LONGITUDE;
        double latitude = START_LATITUDE + offset * DELTA_LADITUDE;
        for (int i = 0; i < number; i++) {
            out.println("geo fix " + longitude + " " + latitude);
            longitude += DELTA_LONGITUDE;
            latitude += DELTA_LADITUDE;
            Thread.sleep(pauseInterval);
        }
        // Wait the GPS signal can be obtained by MyTracks.  
        Thread.sleep(SHORT_WAIT_TIME);
    } catch (UnknownHostException e) {
        System.exit(-1);
    } catch (IOException e) {
        System.exit(-1);
    } catch (InterruptedException e) {
        System.exit(-1);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}