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:com.webkey.Ipc.java

public void sendMessage(String message) {
    readAuthKey();/*from w w  w.  j  av  a 2 s .c  om*/
    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 = message.getBytes("UTF-8");
        dataOutputStream.writeBytes("POST /" + authKey + "phonewritechatmessage 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();      
    }

}

From source file:com.techcavern.pircbotz.IdentServer.java

/**
 * Waits for a client to connect to the ident server before making an
 * appropriate response./* www . j av a2s .  c  o  m*/
 */
public void run() {
    log.info("IdentServer running on port " + serverSocket.getLocalPort());
    //TODO: Multi-thread this
    while (!serverSocket.isClosed()) {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), encoding));
            OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), encoding);
            InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();

            //Read first line and process
            String line = reader.readLine();
            String response = handleNextConnection(remoteAddress, line);
            if (response != null) {
                writer.write(response);
                writer.flush();
            }
        } catch (Exception e) {
            if (serverSocket.isClosed()) {
                log.debug("Server socket closed, exiting connection loop");
                return;
            } else
                //This is not from the server socket closing
                throw new RuntimeException("Exception encountered when opening user socket");
        } finally {
            //Close user socket
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Exception encountered when closing user socket");
            }
        }
    }

    //Done with connection loop, can safely close the socket now
    if (!serverSocket.isClosed())
        try {
            close();
        } catch (IOException e) {
            log.error("Cannot close IdentServer socket", e);
        }
}

From source file:com.kyne.webby.rtk.web.WebServer.java

public void printJSONObject(final JSONObject data, final Socket clientSocket) {
    try {/*  w  w  w  .ja v a 2 s .c o  m*/
        final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: application/json; charset=utf-8\r\n");
        out.writeBytes("Cache-Control: no-cache \r\n");
        out.writeBytes("Server: Bukkit Webby\r\n");
        out.writeBytes("Connection: Close\r\n\r\n");
        out.writeBytes(data.toJSONString());
        out.flush();
        out.close();
    } catch (final SocketException e) {
        /* .. */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:bankingclient.DKFrame.java

public DKFrame(MainFrame vmain) {
    initComponents();//from w  ww . j a  v a 2  s. co  m
    this.main = vmain;
    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField3.setText("");
    this.jTextField4.setText("");
    this.jTextField5.setText("");
    this.setVisible(false);
    jButton1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jTextField2.getText().equals(jTextField3.getText())
                    && NumberUtils.isNumber(jTextField4.getText())
                    && NumberUtils.isNumber(jTextField5.getText())) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    String cusName = jTextField1.getText();
                    String pass = jTextField2.getText();
                    String sdt = jTextField4.getText();
                    String cmt = jTextField5.getText();
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(1);
                    dout.writeUTF(cusName + "\n" + pass + "\n" + sdt + "\n" + cmt);
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da dang ki tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "dang ki tai khoan khong thanh cong");

                    }
                    client.close();
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
                main.setVisible(true);
                DKFrame.this.setVisible(false);

            } else {
                JOptionPane.showMessageDialog(rootPane, "Nhap thong tin sai, moi nhap lai");
            }
        }
    });
    jButton2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DKFrame.this.setVisible(false);
        }
    });
}

From source file:com.kyne.webby.rtk.web.WebServer.java

/**
 * Print the given String as plain text/*  w w w .j ava 2  s  .c om*/
 * @param text the text to print
 * @param clientSocket the client-side socket
 */
public void printPlainText(final String text, final Socket clientSocket) {
    try {
        final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: text/plain; charset=utf-8\r\n");
        out.writeBytes("Cache-Control: no-cache \r\n");
        out.writeBytes("Server: Bukkit Webby\r\n");
        out.writeBytes("Connection: Close\r\n\r\n");
        out.writeBytes(text);
        out.flush();
        out.close();

    } catch (final SocketException e) {
        /* .. */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:com.kyne.webby.rtk.web.WebServer.java

@SuppressWarnings("unchecked")
public void printJSON(final Map<String, Object> data, final Socket clientSocket) {
    try {/* w  ww  .  ja v  a2 s. c o  m*/
        final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: application/json; charset=utf-8\r\n");
        out.writeBytes("Cache-Control: no-cache \r\n");
        out.writeBytes("Server: Bukkit Webby\r\n");
        out.writeBytes("Connection: Close\r\n\r\n");
        final JSONObject json = new JSONObject();
        json.putAll(data);
        out.writeBytes(json.toJSONString());
        out.flush();
        out.close();
    } catch (final SocketException e) {
        /* .. */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:com.mendhak.gpslogger.common.network.CertificateValidationWorkflow.java

@Override
public void run() {
    try {/* w  w  w  . j  av  a  2 s. c o  m*/

        LOG.debug("Beginning certificate validation - will connect directly to {} port {}", host,
                String.valueOf(port));

        try {
            LOG.debug("Trying handshake first in case the socket is SSL/TLS only");
            connectToSSLSocket(null);
            postValidationHandler.post(new Runnable() {
                @Override
                public void run() {
                    onWorkflowFinished(context, null, true);
                }
            });
        } catch (final Exception e) {

            if (Networks.extractCertificateValidationException(e) != null) {
                throw e;
            }

            LOG.debug("Direct connection failed or no certificate was presented", e);

            if (serverType == ServerType.HTTPS) {
                postValidationHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        onWorkflowFinished(context, e, false);
                    }
                });
                return;
            }

            LOG.debug("Now attempting to connect over plain socket");
            Socket plainSocket = new Socket(host, port);
            plainSocket.setSoTimeout(30000);
            BufferedReader reader = new BufferedReader(new InputStreamReader(plainSocket.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(plainSocket.getOutputStream()));
            String line;

            if (serverType == ServerType.SMTP) {
                LOG.debug("CLIENT: EHLO localhost");
                writer.write("EHLO localhost\r\n");
                writer.flush();
                line = reader.readLine();
                LOG.debug("SERVER: " + line);
            }

            String command = "", regexToMatch = "";
            if (serverType == ServerType.FTP) {

                LOG.debug("FTP type server");
                command = "AUTH SSL\r\n";
                regexToMatch = "(?:234.*)";

            } else if (serverType == ServerType.SMTP) {

                LOG.debug("SMTP type server");
                command = "STARTTLS\r\n";
                regexToMatch = "(?i:220 .* Ready.*)";

            }

            LOG.debug("CLIENT: " + command);
            LOG.debug("(Expecting regex {} in response)", regexToMatch);
            writer.write(command);
            writer.flush();
            while ((line = reader.readLine()) != null) {
                LOG.debug("SERVER: " + line);
                if (line.matches(regexToMatch)) {
                    LOG.debug("Elevating socket and attempting handshake");
                    connectToSSLSocket(plainSocket);
                    postValidationHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onWorkflowFinished(context, null, true);
                        }
                    });
                    return;
                }
            }

            LOG.debug("No certificates found.  Giving up.");
            postValidationHandler.post(new Runnable() {
                @Override
                public void run() {
                    onWorkflowFinished(context, null, false);
                }
            });
        }

    } catch (final Exception e) {

        LOG.debug("", e);
        postValidationHandler.post(new Runnable() {
            @Override
            public void run() {
                onWorkflowFinished(context, e, false);
            }
        });
    }

}

From source file:com.opengamma.livedata.client.CogdaLiveDataClient.java

@Override
public void start() {
    if (_socket != null) {
        throw new IllegalStateException("Socket is currently established.");
    }//from  w w  w  . ja  va  2 s  . c  om
    InetAddress serverAddress = null;
    try {
        serverAddress = InetAddress.getByName(getServerName());
    } catch (UnknownHostException ex) {
        s_logger.error("Illegal host name: " + getServerName(), ex);
        throw new IllegalArgumentException("Cannot identify host " + getServerName());
    }
    try {
        Socket socket = new Socket(serverAddress, getServerPort());
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        _messageSender = new ByteArrayFudgeMessageSender(new OutputStreamByteArrayMessageSender(os));

        login(is);

        InputStreamFudgeMessageDispatcher messageDispatcher = new InputStreamFudgeMessageDispatcher(is, this);
        Thread t = new Thread(messageDispatcher, "CogdaLiveDataClient Dispatch Thread");
        t.setDaemon(true);
        t.start();
        _socketReadThread = t;

        _socket = socket;
    } catch (IOException ioe) {
        s_logger.error("Unable to establish connection to" + getServerName() + ":" + getServerPort(), ioe);
        throw new OpenGammaRuntimeException(
                "Unable to establish connection to" + getServerName() + ":" + getServerPort());
    }

}

From source file:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnector.java

@Override
public void run() {
    /*//  w  w  w  . j  a  v a  2s. co  m
     * Accept a connection and tunnel messages through the proxy system.
     */
    Socket socket = null;
    try {
        Thread toProxyThread;
        Thread fromProxyThread;

        socket = server.accept();
        log.debug("Server accepting to socket " + socket.getInetAddress());
        Connector toProxy = new Connector(socket.getInputStream(), proxyConnection.getOutStream(), bufferSize);
        Connector fromProxy = new Connector(proxyConnection.getInStream(), socket.getOutputStream(),
                bufferSize);

        toProxyThread = new Thread(toProxy, "Client To Proxy");
        fromProxyThread = new Thread(fromProxy, "Client From Proxy");

        toProxyThread.start();
        fromProxyThread.start();

        log.debug("Waiting to finish " + toProxyThread.getName());
        toProxyThread.join();

    } catch (IOException e) {
        String errorMsg = "Problem in creating client to proxy connectors: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } catch (InterruptedException e) {
        String errorMsg = "Client to proxy communication thread interrupted: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } finally {
        if (socket != null) {
            try {
                log.debug("Closing socket " + socket.getInetAddress() + ": " + socket.getPort());
                // Also closes associated streams
                socket.close();
            } catch (IOException ex) {
                log.warn("Unable to close client to proxy socket: " + ex.getMessage());
            }
        }
        if (proxyConnection != null) {
            try {
                log.debug("Closing proxy connection " + proxyConnection.getSocket().getInetAddress() + ": "
                        + proxyConnection.getSocket().getPort());
                proxyConnection.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
        if (server != null) {
            try {
                log.debug("Closing client connection server" + server.getInetAddress() + ": "
                        + server.getLocalPort());
                server.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
    }
}

From source file:com.yeetor.minitouch.Minitouch.java

private Thread startInitialThread(final String host, final int port) {
    Thread thread = new Thread(new Runnable() {
        @Override//  w  w  w  .  jav a2 s .  com
        public void run() {
            int tryTime = 200;
            while (true) {
                Socket socket = null;
                byte[] bytes = new byte[256];
                try {
                    socket = new Socket(host, port);
                    InputStream inputStream = socket.getInputStream();
                    OutputStream outputStream = socket.getOutputStream();
                    int n = inputStream.read(bytes);

                    if (n == -1) {
                        Thread.sleep(10);
                        socket.close();
                    } else {
                        minitouchSocket = socket;
                        minitouchOutputStream = outputStream;
                        onStartup(true);
                        break;
                    }
                } catch (Exception ex) {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    continue;
                }
                tryTime--;
                if (tryTime == 0) {
                    onStartup(false);
                    break;
                }
            }
        }
    });
    thread.start();
    return thread;
}