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.hazelcast.stabilizer.Utils.java

public static String getHostAddress() {
    if (hostAddress != null) {
        return hostAddress;
    }/*from w w  w.java2  s .  co m*/

    synchronized (Utils.class) {
        try {
            if (hostAddress != null) {
                return hostAddress;
            }
            Socket s = new Socket("google.com", 80);
            hostAddress = s.getLocalAddress().getHostAddress();
            s.close();
            return hostAddress;
        } catch (IOException io) {
            throw new RuntimeException(io);
        }
    }
}

From source file:UseFactory.java

public Socket createSocket(InetAddress host, int port) throws IOException {

        System.out.println("[creating a custom socket (method 3)]");
        return new Socket(host, port);
    }/*from  w  w  w  . j  ava2  s  .  c o  m*/

From source file:com.stacksync.desktop.Stacksync.java

private static boolean isAlreadyRunning() {
    try {/*from   w w w .  ja v a 2s . c o m*/
        Socket clientSocket = new Socket("localhost", Constants.COMMANDSERVER_PORT);
        clientSocket.close();
        return true;
    } catch (UnknownHostException ex) {
        System.out.println("Error not found localhost. Exception: " + ex.getMessage());
        return false;
    } catch (IOException ex) {
        //System.out.println("Error with socket. Exception: " + ex.getMessage());
        return false;
    }
}

From source file:sample.ClientConfig.java

boolean waitForCacheServerToStart(final String host, final int port, long duration) {
    return waitOnCondition(new Condition() {
        AtomicBoolean connected = new AtomicBoolean(false);

        public boolean evaluate() {
            Socket socket = null;

            try {
                // NOTE: this code is not intended to be an atomic, compound action (a
                // possible race condition);
                // opening another connection (at the expense of using system
                // resources) after connectivity
                // has already been established is not detrimental in this use case
                if (!connected.get()) {
                    socket = new Socket(host, port);
                    connected.set(true);
                }//from  w  w w . ja v  a  2  s .c  o  m
            } catch (IOException ignore) {
            } finally {
                GemFireUtils.close(socket);
            }

            return connected.get();
        }
    }, duration);
}

From source file:com.webkey.Ipc.java

public void comBinAuth(String turl, String postData) {
    readAuthKey();/*from w w w.  ja va2 s .c  o  m*/
    try {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
        port = prefs.getString("port", "80");
        Socket s = new Socket("127.0.0.1", Integer.parseInt(port));

        //outgoing stream redirect to socket
        DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream());
        byte[] utf = postData.getBytes("UTF-8");
        dataOutputStream.writeBytes("POST /" + authKey + turl + " HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n"
                + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n");
        dataOutputStream.write(utf, 0, utf.length);
        dataOutputStream.flush();
        dataOutputStream.close();
        s.close();
    } catch (IOException e1) {
        //e1.printStackTrace();      
    }
    /*
    //         Log.d(TAG,"post data");
    String target = "http://127.0.0.1:"+port+"/"+authKey+turl;
    //Log.d(TAG,target);
    URL url = new URL(target);
    URLConnection conn = url.openConnection();
    // Set connection parameters.
    conn.setDoInput (true);
    conn.setDoOutput (true);
    conn.setUseCaches (false);
    //Make server believe we are form data...
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    DataOutputStream out = new DataOutputStream (conn.getOutputStream ());
    // Write out the bytes of the content string to the stream.
    out.writeBytes(postData);
    out.flush ();
    out.close ();
    // Read response
    BufferedReader in = new BufferedReader (new InputStreamReader(conn.getInputStream ()));
    String temp;
    String response = null;
    while ((temp = in.readLine()) != null){
    response += temp + "\n";
    }
    temp = null;
    in.close ();
    System.out.println("Server response:\n'" + response + "'");
    }catch(Exception e){
    Log.d(TAG,e.toString());
    }
            
    */
}

From source file:hellomindwavepro.ThinkGearSocket.java

public void start() throws ConnectException {

    try {/*  w  ww.  ja  va  2s  .  c om*/
        neuroSocket = new Socket("127.0.0.1", 13854);
    } catch (ConnectException e) {
        //e.printStackTrace();
        System.out.println("Oi plonker! Is ThinkkGear running?");
        running = false;
        throw e;
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        inStream = neuroSocket.getInputStream();
        outStream = neuroSocket.getOutputStream();
        stdIn = new BufferedReader(new InputStreamReader(neuroSocket.getInputStream()));
        running = true;
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (appName != "" && appKey != "") {
        JSONObject appAuth = new JSONObject();
        try {
            appAuth.put("appName", appName);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            appAuth.put("appKey", appKey);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //throws some error
        sendMessage(appAuth.toString());
        System.out.println("appAuth" + appAuth);
    }

    JSONObject format = new JSONObject();
    try {
        format.put("enableRawOutput", true);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        System.out.println("raw error");
        e.printStackTrace();
    }
    try {
        format.put("format", "Json");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        System.out.println("Json error");
        e.printStackTrace();
    }
    //System.out.println("format "+format);
    sendMessage(format.toString());
    t = new Thread(this);
    t.start();

}

From source file:org.openmrs.module.pacsintegration.component.HL7ListenerComponentTest.java

@Test
public void shouldListenForAndParseORU_R01MessageMissingProcedureCode() throws Exception {

    ModuleActivator activator = new PacsIntegrationActivator();
    activator.started();// www.j av a2s  .  c om
    Context.getService(PacsIntegrationService.class).initializeHL7Listener();

    List<Patient> patients = patientService.getPatients(null, "101-6",
            Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true);
    assertThat(patients.size(), is(1)); // sanity check
    Patient patient = patients.get(0);
    List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null,
            Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()), null, null, null,
            false);
    assertThat(encounters.size(), is(0)); // sanity check

    try {
        String message = "MSH|^~\\&|HMI|Mirebalais Hospital|RAD|REPORTS|20130228174549||ORU^R01|RTS01CE16055AAF5290|P|2.3|\r"
                + "PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" + "PV1|1||||||||||||||||||\r"
                + "OBR|1||0000001297||||20130228170556||||||||||||MBL^CR||||||F|||||||M123&Goodrich&Mark&&&&||||20130228170556\r"
                + "OBX|1|TX|127689^SOME_X-RAY||Clinical Indication: ||||||F\r";

        Thread.sleep(2000); // give the simple server time to start

        Socket socket = new Socket("127.0.0.1", 6665);

        PrintStream writer = new PrintStream(socket.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer.print(header);
        writer.print(message);
        writer.print(trailer + "\r");
        writer.flush();

        Thread.sleep(2000);

        // confirm that report encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests)
        encounters = encounterService.getEncounters(patient, null, null, null, null,
                Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()), null, null,
                null, false);
        assertThat(encounters.size(), is(1));
        assertThat(encounters.get(0).getObs().size(), is(3)); // only 3 because no procedure obs

        // confirm that the proper ack is sent out
        String response = reader.readLine();
        assertThat(response, containsString("|ACK|"));
    } finally {
        activator.stopped();
    }

}

From source file:edu.bsu.issgame.java.IssGameJava.java

@Override
public RFuture<Boolean> startGameService() {
    final RPromise<Boolean> promise = RPromise.create();
    try {/*from www  .ja  v  a 2s.  c o  m*/
        server = new Server(executorService, new SocketConnectionAccepter(NetworkInterface.PORT),
                "Expedition Java", versionCode);
    } catch (IOException e) {
        e.printStackTrace();
    }
    server.onServerStart().connect(new UnitSlot() {
        @Override
        public void onEmit() {
            promise.succeed(true);
            startClientAsync();
        }

        private void startClientAsync() {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        log().debug("Starting up the local client.");
                        InetAddress localhost = InetAddress.getLocalHost();
                        Socket socket = new Socket(localhost, NetworkInterface.PORT);
                        MessageIO io = MessageIO.SocketAdapter.inClientMode(socket);
                        Client client = Client.withIO(io).withVersionCode(versionCode);
                        clientCreated.emit(client);
                        executorService.execute(client);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    });
    executorService.execute(server);
    return promise;
}

From source file:docs.AbstractGemFireIntegrationTests.java

protected static boolean waitForCacheServerToStart(final String host, final int port, long duration) {
    return waitOnCondition(new Condition() {
        AtomicBoolean connected = new AtomicBoolean(false);

        public boolean evaluate() {
            Socket socket = null;

            try {
                if (!connected.get()) {
                    socket = new Socket(host, port);
                    connected.set(true);
                }//from w  w w.  j  a  v  a  2  s. c o m
            } catch (IOException ignore) {
            } finally {
                GemFireUtils.close(socket);
            }

            return connected.get();
        }
    }, duration);
}

From source file:com.sixt.service.framework.registry.consul.RegistrationManager.java

protected void unregisterService() {
    if (!isRegistered.get()) {
        return;/*from   w  w w .  j  av a  2s .  co  m*/
    }
    try {
        logger.info("Unregistering {}", serviceName);
        String registryServer = serviceProps.getRegistryServer();
        int colon = registryServer.indexOf(':');
        String hostname = registryServer.substring(0, colon);
        int port = Integer.parseInt(registryServer.substring(colon + 1));
        Socket sock = new Socket(hostname, port);
        OutputStream out = sock.getOutputStream();
        out.write(unregisterString.getBytes());
        out.flush();
        sock.close();

        if (isShutdownHookRegistered.get()) {
            isShutdownHookRegistered.set(false);
        }
    } catch (Exception ex) {
        logger.error("Error unregistering from consul", ex);
    }
}