Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:net.arccotangent.pacchat.net.Client.java

public static void sendMessage(String msg, String ip_address) {
    client_log.i("Sending message to " + ip_address);
    client_log.i("Connecting to server...");

    PublicKey pub;/*from   w  w w .  j  a v  a2s.c  o m*/
    PrivateKey priv;
    Socket socket;
    BufferedReader input;
    BufferedWriter output;

    client_log.i("Checking for recipient's public key...");
    if (KeyManager.checkIfIPKeyExists(ip_address)) {
        client_log.i("Public key found.");
    } else {
        client_log.i("Public key not found, requesting key from their server.");
        try {
            Socket socketGetkey = new Socket();
            socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
            BufferedReader inputGetkey = new BufferedReader(
                    new InputStreamReader(socketGetkey.getInputStream()));
            BufferedWriter outputGetkey = new BufferedWriter(
                    new OutputStreamWriter(socketGetkey.getOutputStream()));

            outputGetkey.write("301 getkey");
            outputGetkey.newLine();
            outputGetkey.flush();

            String pubkeyB64 = inputGetkey.readLine();
            byte[] pubEncoded = Base64.decodeBase64(pubkeyB64);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            outputGetkey.close();
            inputGetkey.close();

            KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            client_log.e("Error saving recipient's key!");
            e.printStackTrace();
        }
    }

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        client_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        client_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        client_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        client_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    pub = KeyManager.loadKeyByIP(ip_address);
    priv = Main.getKeypair().getPrivate();

    String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv);
    try {
        client_log.i("Sending message to recipient.");
        output.write("200 encrypted message");
        output.newLine();
        output.write(cryptedMsg);
        output.newLine();
        output.flush();

        String ack = input.readLine();
        switch (ack) {
        case "201 message acknowledgement":
            client_log.i("Transmission successful, received server acknowledgement.");
            break;
        case "202 unable to decrypt":
            client_log.e(
                    "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update.");
            kuc_id++;
            KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address);
            kuc.start();
            break;
        case "203 unable to verify":
            client_log.w("**********************************************");
            client_log.w(
                    "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!");
            client_log.w(
                    "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
            client_log.w(
                    "If you are sure the connection was not tampered with, consider requesting a key update.");
            client_log.w("**********************************************");
            break;
        case "400 invalid transmission header":
            client_log.e(
                    "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers.");
            break;
        default:
            client_log.w("Server responded with unexpected code: " + ack);
            client_log.w("Transmission might not have been successful.");
            break;
        }

        output.close();
        input.close();
    } catch (IOException e) {
        client_log.e("Error sending message to recipient!");
        e.printStackTrace();
    }
}

From source file:io.selendroid.android.impl.DefaultAndroidEmulator.java

private static Map<String, Integer> mapDeviceNamesToSerial() {
    Map<String, Integer> mapping = new HashMap<String, Integer>();
    CommandLine command = new CommandLine(AndroidSdk.adb());
    command.addArgument("devices");
    Scanner scanner;//from  w  w w  . j  a  va  2s  . c  om
    try {
        scanner = new Scanner(ShellCommand.exec(command));
    } catch (ShellCommandException e) {
        return mapping;
    }
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d");
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            String serial = matcher.group(0);

            Integer port = Integer.valueOf(serial.replaceAll("emulator-", ""));
            TelnetClient client = null;
            try {
                client = new TelnetClient(port);
                String avdName = client.sendCommand("avd name");
                mapping.put(avdName, port);
            } catch (AndroidDeviceException e) {
                // ignore
            } finally {
                if (client != null) {
                    client.close();
                }
            }
            Socket socket = null;
            PrintWriter out = null;
            BufferedReader in = null;
            try {
                socket = new Socket("127.0.0.1", port);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                if (in.readLine() == null) {
                    throw new AndroidDeviceException("error");
                }

                out.write("avd name\r\n");
                out.flush();
                in.readLine();// OK
                String avdName = in.readLine();
                mapping.put(avdName, port);
            } catch (Exception e) {
                // ignore
            } finally {
                try {
                    out.close();
                    in.close();
                    socket.close();
                } catch (Exception e) {
                    // do nothing
                }
            }
        }
    }
    scanner.close();

    return mapping;
}

From source file:com.dc.tes.License.java

private static String LicenseServerConnect(Message request) {
    String license = "";
    Socket client = null;
    try {/*from   w w  w  .  java 2s .co  m*/
        client = new Socket(LICENSE_SERVER_IP, LICENSE_SERVER_PORT);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        license = "Lisence?";
        log.error(license);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        license = "Lisence?";
        log.error(license);
    }

    try {
        client.getOutputStream().write(request.Export());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        license = "?Lisence??";
        log.error(license);
    }
    Message response = null;
    try {
        response = new Message(client.getInputStream());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        license = "?Lisence??";
        log.error(license);
    }
    if (response.getInteger(MessageItem.LICENSE.AVAILABLE) == 0) {
        license = "License???"
                + response.getString(MessageItem.LICENSE.MSG);
        log.error(license);
    }
    if (request.getInteger(MessageItem.LICENSE.SIGN) == 0) {
        license = response.getString(MessageItem.LICENSE.LICENSEFILE);
    }
    return license;
}

From source file:Finger.java

public String finger(String host, String users) throws IOException, SocketException {
    String outstring = "";
    int c = 0;//  w w w.j a  v  a 2s.c  o  m
    Socket sock = new Socket(host, 79);
    OutputStream os = sock.getOutputStream();
    InputStream is = sock.getInputStream();
    users = users + "\r\n";
    os.write(users.getBytes("iso8859_1"));
    try {
        while (c != -1) {
            c = is.read();
            if (c != -1)
                outstring += (char) c;
        }
    } catch (IOException e) {
    }
    return outstring;
}

From source file:Whois.java

public String whois(String query, String server) throws IOException {
    Socket sock = new Socket(server, 43);
    int c = 0;//  w  w  w  .  j  a  v  a 2  s  .c  om
    String outstring = "";
    OutputStream os = sock.getOutputStream();
    InputStream is = sock.getInputStream();
    query += "\r\n";
    os.write(query.getBytes("iso8859_1"));
    try {
        while (c != -1) {
            c = is.read();
            if (c != -1)
                outstring += (char) c;
        }
    } catch (IOException e) {
    }
    return outstring;
}

From source file:com.nmote.smpp.TCPLink.java

public TCPLink(Socket socket, Logger log) throws IOException {
    super(socket.getInputStream(), socket.getOutputStream(), log);
    this.socket = socket;
}

From source file:de.root1.logiccollection.offLogicVocESP8266.java

@Override
public void init() {
    this.tt = new TimerTask() {

        @Override// w w  w  .j a  va 2 s  .c om
        public void run() {
            try {
                Socket s = new Socket("nodemcu1", 44444);
                OutputStream out = s.getOutputStream();
                InputStream in = s.getInputStream();
                out.write("\n".getBytes());
                out.flush();

                InputStreamReader isr = new InputStreamReader(in);
                JSONObject data = (JSONObject) JSONValue.parse(isr);
                isr.close();
                out.close();

                int voc = Integer.parseInt(data.get("voc").toString());
                int tvoc = Integer.parseInt(data.get("voc").toString());
                int resistance = Integer.parseInt(data.get("resistance").toString());
                int status = Integer.parseInt(data.get("status").toString());

                log.info("voc={}, tvoc={} resistance={} status={}",
                        new Object[] { voc, tvoc, resistance, status });

                //                    write(ga, String.valueOf(voc));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    };
    setPA("1.1.203");
    t.schedule(tt, 5000, 60000);
    log.info("VOC ESP8266 reader is running.");
}

From source file:br.ufc.mdcc.mpos.net.util.DiscoveryServiceTcpServer.java

@Override
public void clientRequest(Socket connection) throws IOException {
    OutputStream output = connection.getOutputStream();
    InputStream input = connection.getInputStream();

    byte dataBuffer[] = new byte[BUFFER];

    // PS: in this case "-1" mean a close socket in client side
    int read = 0;
    while ((read = input.read(dataBuffer)) != -1) {
        // e.g.: mpos_serv_req_droid:Calculator:5.0.1
        String mposServiceResquest = new String(dataBuffer, 0, read).trim().toLowerCase();
        if (mposServiceResquest.startsWith("mpos_serv_req_droid")) {
            mposServiceReply(output, mposServiceResquest, "android");
        } else if (mposServiceResquest.startsWith("mpos_serv_req_wp")) {
            mposServiceReply(output, mposServiceResquest, "wp");
        }/* w  ww.  ja  v  a 2  s.com*/
    }

    close(input);
    close(output);
}

From source file:WriteDoubleUsingSockets.java

public void init() {
    Date d = new Date();
    // Get the portnumber and servername and allow to be called from a
    // java main program also
    try {//from   ww  w  . j a  v a  2  s . c  om
        String param;
        param = getParameter("PortNumber");
        if (param != null)
            PortNumber = Integer.parseInt(param);
        param = getParameter("ServerName");
        if (param != null)
            ServerName = param;
    } catch (NullPointerException e) { // Must be called from a main ignore
    }
    try {
        Socket skt = new Socket(ServerName, PortNumber);
        os = new DataOutputStream(skt.getOutputStream());
    } catch (Exception e) {
        Label l = new Label(e.toString());
        add(l);
        System.out.println(e);
        return;
    }
    try {
        s = new ObjectOutputStream(os);
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Unable to open stream as an object stream");
    }
    try {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 25; i++) {
            s.writeObject(new Double(i));
        }
        os.close();
        long endTime = System.currentTimeMillis() - startTime;
        Label l = new Label(
                "Writing 25 doubles server took: " + new Long(endTime).toString() + " milliseconds.");
        add(l);
        System.out.println("Object written");
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Unable to write Objects");
    }
}

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);/*  w  w  w  .j av  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();
}