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.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

public void run() {
    long duration, starttime = System.currentTimeMillis();
    Socket destinationSocket = null;
    try {/*from  w ww.j  a v  a2  s.  c om*/
        BufferedOutputStream proxyClientStream = new BufferedOutputStream(proxySocket.getOutputStream());

        // read client request
        HttpRequest request = handleRequest(proxySocket);
        this.request = request;

        // send request to server
        //logger.debug("connecting to: " + request.getHost() + ":" + request.getPort());
        if (!((System.getProperty("http.proxyHost") == null)
                || System.getProperty("http.proxyHost").trim().equals(""))) {
            String proxyHost = System.getProperty("http.proxyHost");
            String proxyPortStr = System.getProperty("http.proxyPort");
            if (proxyPortStr == null || proxyPortStr.trim().equals("")) {
                proxyPortStr = "80";
            }
            int proxyPort = Integer.parseInt(proxyPortStr);
            //logger.debug("connecting via proxy: " + proxyHost + ":" + proxyPort);
            destinationSocket = new Socket(proxyHost, proxyPort);
        } else {
            destinationSocket = new Socket(request.getHost(), request.getPort());
        }
        OutputStream destinationOutputStream = destinationSocket.getOutputStream();
        destinationOutputStream.write(request.getRequest(), 0, request.getRequest().length);
        destinationOutputStream.flush();
        //logger.debug("request sent");

        // read response from server
        HttpResponse response = handleResponse(destinationSocket, proxyClientStream);
        this.response = response;
        destinationSocket.close();
        destinationSocket = null;

        // send response to client
        proxyClientStream.flush();
        proxySocket.close();
        proxySocket = null;
        duration = System.currentTimeMillis() - starttime;
        //logger.debug("duration: " + duration);
        String path = "http://" + request.getHost()
                + ((request.getPort() == 80) ? "" : (":" + request.getPort())) + request.getPath();
        proxy.setWorkerResult(request.getMethod(), String.valueOf(response.getStatusCode()), path, starttime,
                request.getRequest(), this.response.getResponse(), duration);
    } catch (Exception e) {
        //logger.error("Error occurred: " + e.toString());
        duration = System.currentTimeMillis() - starttime;
        if (request != null) {
            String path = "http://" + request.getHost()
                    + ((request.getPort() == 80) ? "" : (":" + request.getPort())) + request.getPath();
            if (response != null && response.getResponse() != null) {
                proxy.setWorkerResult(request.getMethod(), String.valueOf(response.getStatusCode()), path,
                        starttime, request.getRequest(), response.getResponse(), duration);
            } else {
                proxy.setWorkerResult(request.getMethod(), "XXX", path, starttime, request.getRequest(),
                        ("no response available - " + e.toString()).getBytes(), duration);
            }
        } else {
            proxy.setWorkerResult("---", "---", "---", starttime, e.toString().getBytes(),
                    "no response available".getBytes(), duration);
        }
        try {
            if (proxySocket != null) {
                closeSocket(proxySocket);
            }
        } finally {
            if (destinationSocket != null) {
                closeSocket(destinationSocket);
            }
        }
    }
}

From source file:org.openbaton.integration.test.utils.Utils.java

public static boolean available(String host, String port) {
    try {//from   ww  w  . j a v  a2  s. co  m
        Socket s = new Socket(host, Integer.parseInt(port));
        log.info("Server is listening on port " + port + " of " + host);
        s.close();
        return true;
    } catch (IOException ex) {
        // The remote host is not listening on this port
        log.warn("Server is not listening on port " + port + " of " + host);
        return false;
    }
}

From source file:de.burrotinto.jKabel.dbauswahlAS.DBAuswahlAAS.java

public IStatusClient getStatusClient() throws IOException {
    return new StatusClient(new Socket(serverIP, StatusServer.PORT));
}

From source file:com.oracle.jes.samples.hellostorage.HttpElementPost.java

public void putData2() throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("192.168.1.5", 8080);
    coreContext.setTargetHost(host);/*from ww  w .ja va  2 s .c  o m*/

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {

        HttpEntity[] requestBodies = {
                new StringEntity("This is the first test request",
                        ContentType.create("text/plain", Consts.UTF_8)),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8"),
                        ContentType.APPLICATION_OCTET_STREAM),
                new InputStreamEntity(
                        new ByteArrayInputStream(
                                "This is the third test request (will be chunked)".getBytes("UTF-8")),
                        ContentType.APPLICATION_OCTET_STREAM) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    "/servlets-examples/servlet/RequestInfoExample");

            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:com.twinflag.coofiletouch.AuthorityChecking.java

private void fetchLicenseFromInternet() {
    Log.i(TAG, "===fetchLicenseFromInternet !");
    new Thread() {
        public void run() {
            try {
                JSONObject json = new JSONObject();
                try {
                    int readLength = 0;
                    int sendSize = 0;
                    json.put("command", "checkLicense");
                    json.put("hardinfo", DeviceUtil.getDeviceInfo());

                    Socket socket = new Socket("192.168.13.95", 60000);

                    // ?
                    OutputStream os = socket.getOutputStream();
                    String jsonStr = json.toString();
                    byte[] buffer = jsonStr.getBytes("UTF-8");
                    sendSize = buffer.length;
                    byte[] array = new byte[4];
                    array[3] = (byte) (0xff & sendSize);
                    array[2] = (byte) ((0xff00 & sendSize) >> 8);
                    array[1] = (byte) ((0xff0000 & sendSize) >> 16);
                    array[0] = (byte) (0xff000000 & sendSize >> 24);
                    os.write(array);/*  w  ww.  ja  va 2s. c  o m*/
                    os.flush();
                    os.write(buffer);
                    os.flush();

                    // ;
                    InputStream inputStream = socket.getInputStream();
                    byte[] length = new byte[4];
                    byte[] temp = new byte[4];
                    byte oneByte;
                    try {
                        inputStream.read(length);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    for (int i = 0; i < 4; i++) {
                        temp[3 - i] = length[i];
                    }
                    for (int j = 0; j < 4; j++) {
                        oneByte = temp[j];
                        readLength += (oneByte & 0xFF) << (8 * j);
                    }

                    System.out.println(readLength + "?");

                    if (readLength == 0) {
                        System.out.println("readLength == 0");
                        Message msg = Message.obtain();
                        msg.what = MSG_GET_LINCENSE_FROM_INTERNET;
                        msg.obj = null;
                        mHandler.sendMessageDelayed(msg, 100);
                    }
                    // ??0
                    else {
                        System.out.println("readLength == " + readLength);
                        buffer = new byte[readLength];
                        try {
                            String receivedContent = null;
                            inputStream.read(buffer, 0, readLength);
                            receivedContent = new String(buffer, "UTF-8");

                            Message msg = Message.obtain();
                            msg.what = MSG_GET_LINCENSE_FROM_INTERNET;
                            msg.obj = receivedContent;
                            mHandler.sendMessageDelayed(msg, 100);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    socket.close();

                } catch (JSONException exception) {
                    exception.printStackTrace();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();

}

From source file:com.criptext.socket.DarkStarSocketClient.java

/**
 * @see DarkStarClient#connect()//ww w  .  j a v  a2  s  . c  o  m
 *
 * @throws java.io.IOException
 */
public void connect() throws IOException {

    //s = (SocketConnection) Connector.open("socket://" + this.host + ":" + this.port+"?"+ConnectionType.getConnectionString(), Connector.READ_WRITE);
    try {
        s = new Socket(this.host, this.port);
        s.setReceiveBufferSize(2048 * 2048);
        s.setSendBufferSize(2048 * 2048);
        //Log.d("DarkStarSocketClient - connect", "creando socket s:"+ s+"host"+this.host+"port"+this.port);

    } catch (Exception e) {
        System.out.println(e.toString());
    }

    DataInputStream in = new DataInputStream(s.getInputStream());
    //Log.d("DarkStarSocketClient - connect", "definiendo in: "+in);
    DataOutputStream out = new DataOutputStream(s.getOutputStream());
    //Log.d("DarkStarSocketClient - connect", "definiendo out: "+out);

    reader = new InputReader(this, in);
    //Log.d("DarkStarSocketClient - connect", "reader: "+reader);
    writer = new OutputWriter(this, out);
    //Log.d("DarkStarSocketClient - connect", "writer: "+writer);
    new Thread(reader).start();
    //Log.d("DarkStarSocketClient - connect", "Empezar hilo reader");
    new Thread(writer).start();
    //Log.d("DarkStarSocketClient - connect", "Empezar hilo writer");

    //give the threads some time to set-up (should be done in a better way)
    try {
        //Log.d("DarkStarSocketClient - connect", "Empieza suspension del hilo durante 1000 (s)");
        Thread.sleep(1000);
        //Log.d("DarkStarSocketClient - connect", "Terminaron los 1000 (s) de la suspension del hilo");
    } catch (InterruptedException ex) {
        //Log.d("DarkStarSocketClient - connect", "Exception: "+ex);
        ex.printStackTrace();
    }
}

From source file:dk.netarkivet.viewerproxy.WebProxyTester.java

@After
public void tearDown() {
    if (proxy != null) {
        proxy.kill();//from  ww  w.j  a va  2  s.  c om
    }
    // Check port not in use (since this might break later tests)
    try {
        new Socket(InetAddress.getLocalHost(), httpPort);
        fail("Port still in use after killing server");
    } catch (IOException e) {
        // expected
    }
}

From source file:be.tutul.naheulcraft.launcher.auth.Auth.java

public void logIn() {
    new Thread() {
        private Socket ss;
        private BufferedReader in;
        private PrintWriter out;

        public void run() {
            try {
                InetAddress adresse = InetAddress.getByName("naheulcraft.be"); // Rcupre l'adresse IP
                String IP = adresse.toString().split("/")[1];
                Auth.this.logger.info("Connexion  " + IP + ":" + Variables.PORT);
                this.ss = new Socket(IP, Variables.PORT);

                this.in = new BufferedReader(new InputStreamReader(this.ss.getInputStream()));
                this.out = new PrintWriter(this.ss.getOutputStream());

                // On signale au serveur qu'on demande une authentification
                this.out.println("<start>");
                this.out.flush();
                String ok = this.in.readLine();
                if (!ok.contains("<ok>")) {
                    Auth.this.launcher.getPanel().getLogInPopup().setText("Rponse innatendu du serveur");
                    Auth.this.launcher.getPanel().getLogInPopup().setCanLogIn(true);
                    Auth.this.launcher.getPanel().showLoginPrompt();
                    return;
                }// w w w  . ja  v a 2  s  .  c  om

                Auth.this.logger.info("Connexion au service de login tablie");

                String key = ok.split("<ok>")[1]; // On rcure la cl
                String msg = Auth.this.launcher.getUser().getPseudo() + ":"
                        + Auth.this.launcher.getUser().getPass() + ":" + Variables.version + "<end>";
                System.err.println("A : " + msg);//TODO
                msg = crypt(msg, key); // On crypt en base 64

                // On lui envoit la requte
                Auth.this.logger.info("Vrification du login en cours...");
                System.err.println("B : " + msg);//TODO
                this.out.println(msg);
                this.out.flush();

                String login = this.in.readLine();
                login = decrypt(login, key); // On dcrypt en string
                System.err.println("C : " + login);//TODO

                // On ferme le socket
                this.in.close();
                this.out.close();
                this.ss.close();

                String ret;
                if (login != null) {
                    if (login.contains("pass")) {
                        ret = "Mauvais mot de passe";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.warning(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("user")) {
                        ret = "Mauvais pseudo";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.warning(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("statut")) {
                        ret = "Compte n'ont autoris";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.warning(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("encodage")) {
                        ret = "Problme dans la demande de login";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.error(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("serveur")) {
                        ret = "Erreur du service de login";
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.logger.error(ret);
                        Auth.this.launcher.getPanel().getLogInPopup().setText(ret);
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    } else if (login.contains("<ok>")) {
                        String id = login.split("<end>")[0].split("<ok>")[1];
                        Auth.this.launcher.getUser().setID(id);
                        Auth.this.launcher.getUser().setLogin(true);
                        Auth.this.logger.info("Login vrifier avec succs");
                        Auth.this.logger.info("ID de connexion : " + id);
                        Auth.this.lastLogin.writeUsername();
                        Auth.this.launcher.getPanel().showPanel();
                        return;
                    } else {
                        Auth.this.logger.error(login);
                        Auth.this.launcher.getUser().setLogin(false);
                        Auth.this.launcher.getPanel().getLogInPopup().setText("Erreur inconnue");
                        Auth.this.launcher.getPanel().showLoginPrompt();
                        return;
                    }
                }
                Auth.this.logger.error("Pas de rponse du serveur");
                Auth.this.launcher.getUser().setLogin(false);
                Auth.this.launcher.getPanel().getLogInPopup().setText("Pas de rponse");
                Auth.this.launcher.getPanel().showLoginPrompt();
            } catch (Exception e) {
                Auth.this.logger.fatal("Impossible de communiquer avec le service de login", e);
                Auth.this.launcher.getUser().setLogin(false);
                Auth.this.launcher.getPanel().getLogInPopup().setText("Problme de communication");
                Auth.this.launcher.getPanel().showLoginPrompt();
                try { // On tente quand mme de couper le socket
                    this.in.close();
                    this.out.close();
                    this.ss.close();
                } catch (Exception ingnored) {
                }
            }
        }
    }.start();
}

From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java

@Test
public void testEchoServer() throws IOException {
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(/*from   w ww  .j  ava 2 s.  c o m*/
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            .withConnectorFactory(TcpConnectorFactory.Builder.builder()
                    .withConnectedSocketTask(new TcpConnectTestHandler()).build())
            .build();
    simpleNbServer.start();
    String message1 = "this is message1";
    String message2 = "this is message2";
    try {
        Socket socket = new Socket("localhost", 1111);
        OutputStream out = socket.getOutputStream();
        InputStream in = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

        // message1
        out.write((message1 + '\n').getBytes(StandardCharsets.UTF_8));
        String messageRead1 = reader.readLine();
        Assert.assertEquals(message1, messageRead1);

        // message2
        out.write((message2 + '\n').getBytes(StandardCharsets.UTF_8));
        String messageRead2 = reader.readLine();
        Assert.assertEquals(message2, messageRead2);

        // quit
        out.write("quit\n".getBytes(StandardCharsets.UTF_8));
        String finalMessage = reader.readLine();
        Assert.assertNull(finalMessage);
    } finally {
        simpleNbServer.shutdown();
    }
}