Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:net.mohatu.bloocoin.miner.RegisterClass.java

private void register() {
    try {/*ww w  .  j a va 2s .  com*/
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            MainView.updateStatusText("Registration failed. ");
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        System.out.println("Error: Unknown host.");
    } catch (IOException e) {
        System.out.println("Error: Network error.");
    }
}

From source file:org.apache.camel.component.smpp.SmppConnectionFactory.java

private void connectProxy(String host, int port, Socket socket) throws IOException {
    try {/*from ww w.j  a  v a 2s.c  o m*/
        OutputStream out = socket.getOutputStream();
        InputStream in = socket.getInputStream();

        String connectString = "CONNECT " + host + ":" + port + " HTTP/1.0\r\n";
        out.write(connectString.getBytes());

        String username = config.getHttpProxyUsername();
        String password = config.getHttpProxyPassword();

        if (username != null && password != null) {
            String usernamePassword = username + ":" + password;
            byte[] code = Base64.encodeBase64(usernamePassword.getBytes());
            out.write("Proxy-Authorization: Basic ".getBytes());
            out.write(code);
            out.write("\r\n".getBytes());
        }

        out.write("\r\n".getBytes());
        out.flush();

        int ch = 0;

        BufferedReader reader = IOHelper.buffered(new InputStreamReader(in));
        String response = reader.readLine();
        if (response == null) {
            throw new RuntimeCamelException("Empty response to CONNECT request to host " + host + ":" + port);
        }
        String reason = "Unknown reason";
        int code = -1;
        try {
            ch = response.indexOf(' ');
            int bar = response.indexOf(' ', ch + 1);
            code = Integer.parseInt(response.substring(ch + 1, bar));
            reason = response.substring(bar + 1);
        } catch (NumberFormatException e) {
            throw new RuntimeCamelException("Invalid response to CONNECT request to host " + host + ":" + port
                    + " - cannot parse code from response string: " + response);
        }
        if (code != 200) {
            throw new RuntimeCamelException("Proxy error: " + reason);
        }

        // read until empty line
        for (; response.length() > 0;) {
            response = reader.readLine();
            if (response == null) {
                throw new RuntimeCamelException("Proxy error: reached end of stream");
            }
        }
    } catch (RuntimeException re) {
        closeSocket(socket);
        throw re;
    } catch (Exception e) {
        closeSocket(socket);
        throw new RuntimeException("SmppConnectionFactory: " + e.getMessage());
    }
}

From source file:MailTest.java

/**
 * Sends the mail message that has been authored in the GUI.
 *//* w w w . j a v  a  2 s.  c  o  m*/
public void sendMail() {
    try {
        Socket s = new Socket(smtpServer.getText(), 25);

        InputStream inStream = s.getInputStream();
        OutputStream outStream = s.getOutputStream();

        in = new Scanner(inStream);
        out = new PrintWriter(outStream, true /* autoFlush */);

        String hostName = InetAddress.getLocalHost().getHostName();

        receive();
        send("HELO " + hostName);
        receive();
        send("MAIL FROM: <" + from.getText() + ">");
        receive();
        send("RCPT TO: <" + to.getText() + ">");
        receive();
        send("DATA");
        receive();
        send(message.getText());
        send(".");
        receive();
        s.close();
    } catch (IOException e) {
        comm.append("Error: " + e);
    }
}

From source file:org.jfree.chart.demo.SocketThread.java

@Override
public void run() {
    // TODO Auto-generated method stub
    try {//from  www.j a v  a2 s  .  c  o m
        ServerSocket ss = new ServerSocket(4444);
        Socket socket = null;
        while (Islive) {
            System.out.println("Started :) ");
            socket = ss.accept(); /*  */
            System.out.println("Got a client :) ");

            InputStream sin = socket.getInputStream();
            OutputStream sout = socket.getOutputStream();

            in = new DataInputStream(sin);
            out = new DataOutputStream(sout);

            String line = null;

            while (true) {
                line = in.readUTF(); /*    */
                System.out.println("line start sending  = " + line);
                out.writeUTF(data);
                out.flush();
                line = in.readUTF();
                System.out.println(line);
                if (line == "finish")
                    break;
                else {
                    out.writeUTF("ok");
                    out.flush();
                }
            }
        }
        out.writeUTF("finish");
        out.flush();

        in.close();
        out.close();
        socket.close();
    } catch (Exception x) {

        errors += x.toString() + " ;\n";
        error_flag = true;
    }

}

From source file:WriteObjectsFromSocket.java

ReaderWriter(Socket rs) {
    // /////////////////////////////////////////////
    // Open a remote stream to the client
    // /////////////////////////////////////////////
    try {//from  w  ww  . ja  va 2s. c om
        is = new DataInputStream(rs.getInputStream());
    } catch (Exception e) {
        System.out.println("Unable to get Stream");
        return;
    }
    // /////////////////////////////////////////////
    // Open the file that is to be written to
    // /////////////////////////////////////////////
    try {
        File theFile = new File("/tmp", "Objects");
        System.out.println("The file to be created or overwritten: " + theFile);
        localFile = new FileOutputStream(theFile);
    } catch (IOException e) {
        System.out.println("Open error " + e);
        return;
    }
    // ///////////////////////////////////////////
    // Look for all the double data constantly
    // ///////////////////////////////////////////
    while (writeloop) {
        // Look for data if we get here that is requests
        try {
            inputByte = is.readByte(); // Not the best way to do it
            // Consider looking for available bytes
            // and reading that amount.
        } catch (IOException e) {
            System.out.println("In the read loop:" + e);
            writeloop = false;
        }
        // ///////////////////////////
        // We did get something
        // Write The Data
        // ///////////////////////////
        try {
            localFile.write(inputByte);
        } catch (IOException e) {
            System.out.println("Write failed");
            writeloop = false;
        }
    }
    // ////////////////////////////////
    // Close the connection and file
    // ////////////////////////////////
    try {
        rs.close();
        is.close();
        localFile.close();
    } catch (Exception e) {
        System.out.println("Unable to close ");
    }
    System.out.println("Thread exiting");
}

From source file:com.googlecode.android_scripting.jsonrpc.JsonRpcServerTest.java

public void testValidHandshake() throws IOException, JSONException {
    JsonRpcServer server = new JsonRpcServer(null, "foo");
    InetSocketAddress address = server.startLocal(0);
    Socket client = new Socket();
    client.connect(address);//from   www. ja v  a 2  s . c om
    PrintStream out = new PrintStream(client.getOutputStream());
    out.println(buildRequest(0, "_authenticate", Lists.newArrayList("foo")));
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    JSONObject response = new JSONObject(in.readLine());
    Object error = response.get("error");
    assertEquals(JSONObject.NULL, error);
    client.close();
    server.shutdown();
}

From source file:Clases.cCifrado.java

public String pedirClave(String dato) {

    String clave = "";
    Scanner sc = new Scanner(System.in);
    Socket socket;
    try {//from   w w w.j  a  v  a2 s.co m
        String ipServidor = receptor;
        int pto = puerto;
        System.out.println("conectando con el servidor...");
        socket = new Socket(ipServidor, pto);
        Scanner entrada = new Scanner(socket.getInputStream());
        PrintStream salidaServer = new PrintStream(socket.getOutputStream());
        salidaServer.println(dato);
        clave = entrada.nextLine();
        System.out.println("Dato recibido: " + clave);
        socket.close();

    } catch (IOException ex) {
        System.err.println("Cliente> " + ex.getMessage());
    }
    return clave;
}

From source file:net.mohatu.bloocoin.miner.RegCustom.java

private void register() {
    try {//from w w  w.j  av a2s .c  om
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            JOptionPane.showMessageDialog(Main.scrollPane,
                    "Registration failed.\nCheck your network connection", "Registration Failed",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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   w w  w  .  j  ava2  s .c  o m

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

    return socket;
}

From source file:no.antares.clutil.hitman.MessageChannel.java

/** Blocks while waiting for message */
protected Message waitForNextMessage() {
    Socket clientSocket = null;
    BufferedReader in = null;/*  w  w w  .  j  a  v a  2  s .  co m*/
    PrintWriter out = null;
    try {
        clientSocket = serverSocket.accept();
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine = in.readLine();
        if (inputLine != null) {
            String reply = reply2(inputLine);
            if (!StringUtils.isBlank(reply)) {
                out = new PrintWriter(clientSocket.getOutputStream(), true);
                out.println(reply);
            }
            Message msg = new Message(inputLine);
            return msg;
        }
    } catch (IOException e) {
        logger.error("waitForNextMessage() got Exception", e);
    } finally {
        close(clientSocket);
        close(out);
        close(in);
    }
    return Message.EMPTY;
}