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:Main.java

public void run() {
    while (true) {
        try {//  w  w w . java  2s .com
            System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();

            System.out.println("Just connected to " + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            System.out.println(in.readUTF());

            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");

            server.close();
        } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }
}

From source file:any.Connection.java

public Connection(String name, Linker service, Socket socket) throws InterruptedException, IOException {
    this.service = service;

    out = socket.getOutputStream();
    in = socket.getInputStream();//from  w w  w  .j  a v a2  s .  c  o  m

    // br.mark(256);
    Thread.sleep(100);

    outThread = new OutThread(out, this);
    inThread = new InThread(in, this);

    outThread.setName(outThread.getName() + " " + name + " (out con)");
    inThread.setName(inThread.getName() + " " + name + "  (in con)");

    inThread.start();
    outThread.start();
    // setup and negotiation, send available protocols first

    logger.info("+SERVICE: new connection established with name " + name);
}

From source file:com.talis.platform.sequencing.zookeeper.ZkTestHelper.java

public boolean waitForServerDown(String hp, long timeout) {
    long start = System.currentTimeMillis();
    String split[] = hp.split(":");
    String host = split[0];/*from  w  ww. j a v  a 2 s. c  om*/
    int port = Integer.parseInt(split[1]);
    while (true) {
        try {
            Socket sock = new Socket(host, port);
            try {
                OutputStream outstream = sock.getOutputStream();
                outstream.write("stat".getBytes());
                outstream.flush();
            } finally {
                sock.close();
            }
        } catch (IOException e) {
            return true;
        }

        if (System.currentTimeMillis() > start + timeout) {
            break;
        }
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            // ignore
        }
    }
    return false;
}

From source file:SimpleHttpServerDataProvider.java

public SimpleHttpServer(SimpleHttpServerDataProvider dataProvider, int port) {

    class SocketProcessor implements Runnable {
        private Socket s;
        private InputStream is;
        private OutputStream os;
        private SimpleHttpServerDataProvider dataProvider;

        private SocketProcessor(Socket s, SimpleHttpServerDataProvider prov) throws Throwable {
            this.dataProvider = prov;
            this.s = s;
            this.is = s.getInputStream();
            this.os = s.getOutputStream();
        }/*from w  w  w  . j  av a  2s  . com*/

        public void run() {
            try {
                readInputHeaders();
                writeResponse("");
            } catch (Throwable t) {
                /*do nothing*/
            } finally {
                try {
                    s.close();
                } catch (Throwable t) {
                    /*do nothing*/
                }
            }

        }

        private void writeResponse(String s) throws Throwable {
            String response = "HTTP/1.1 200 OK\r\n" + "Server: DJudge.http\r\n" + "Content-Type: text/html\r\n"
                    + "Content-Length: " + s.length() + "\r\n" + "Connection: close\r\n\r\n";
            String result = response + dataProvider.getHtmlPage("");
            os.write(result.getBytes());
            os.flush();
        }

        private void readInputHeaders() throws Throwable {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String s = br.readLine();
                if (s == null || s.trim().length() == 0) {
                    break;
                }

            }
        }
    }

    this.dataProvider = dataProvider;
    try {
        ServerSocket ss = new ServerSocket(port);

        while (true) {
            Socket s = ss.accept();

            new Thread(new SocketProcessor(s, dataProvider)).start();
        }
    } catch (Exception e) {

    } catch (Throwable e) {

    }
}

From source file:com.brienwheeler.lib.io.ReconnectingSocket.java

private void tryToWrite(byte data[]) {
    Socket writeSocket = socket.get();
    if (writeSocket == null)
        return;//ww  w  . jav  a  2 s  .co m

    try {
        OutputStream outputStream = writeSocket.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
    } catch (IOException e) {
        if (socket.compareAndSet(writeSocket, null)) {
            log.error("error writing to " + hostname, e);
            onDisconnected();
            startConnectThread(reconnectPeriodicity);
            try {
                writeSocket.close();
            } catch (IOException e1) {
                // silent
            }
        }
    }
}

From source file:SocketApplet.java

/** Initialize the GUI nicely. */
public void init() {
    Label aLabel;/*  w  w w. jav  a 2s .c o m*/

    setLayout(new GridBagLayout());
    int LOGO_COL = 1;
    int LABEL_COL = 2;
    int TEXT_COL = 3;
    int BUTTON_COL = 1;
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 100.0;
    gbc.weighty = 100.0;

    gbc.gridx = LABEL_COL;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.EAST;
    add(aLabel = new Label("Name:", Label.CENTER), gbc);
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridx = TEXT_COL;
    gbc.gridy = 0;
    add(nameTF = new TextField(10), gbc);

    gbc.gridx = LABEL_COL;
    gbc.gridy = 1;
    gbc.anchor = GridBagConstraints.EAST;
    add(aLabel = new Label("Password:", Label.CENTER), gbc);
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridx = TEXT_COL;
    gbc.gridy = 1;
    add(passTF = new TextField(10), gbc);
    passTF.setEchoChar('*');

    gbc.gridx = LABEL_COL;
    gbc.gridy = 2;
    gbc.anchor = GridBagConstraints.EAST;
    add(aLabel = new Label("Domain:", Label.CENTER), gbc);
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridx = TEXT_COL;
    gbc.gridy = 2;
    add(domainTF = new TextField(10), gbc);
    sendButton = new Button("Send data");
    gbc.gridx = BUTTON_COL;
    gbc.gridy = 3;
    gbc.gridwidth = 3;
    add(sendButton, gbc);

    whence = getCodeBase();

    // Now the action begins...
    sendButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            String name = nameTF.getText();
            if (name.length() == 0) {
                showStatus("Name required");
                return;
            }
            String domain = domainTF.getText();
            if (domain.length() == 0) {
                showStatus("Domain required");
                return;
            }
            showStatus("Connecting to host " + whence.getHost() + " as " + nameTF.getText());

            try {
                Socket s = new Socket(getCodeBase().getHost(), 3333);
                PrintWriter pf = new PrintWriter(s.getOutputStream(), true);
                // send login name
                pf.println(nameTF.getText());
                // passwd
                pf.println(passTF.getText());
                // and domain
                pf.println(domainTF.getText());

                BufferedReader is = new BufferedReader(new InputStreamReader(s.getInputStream()));
                String response = is.readLine();
                showStatus(response);
            } catch (IOException e) {
                showStatus("ERROR: " + e.getMessage());
            }
        }
    });
}

From source file:com.hulaki.smtp.api.ApiClient.java

private String sendRequestToApiServer(ApiRequest request) {
    try {/*w w  w  .  j  av a2 s. c om*/
        Socket clientSocket = new Socket(this.apiServerHostname, this.apiServerPort);
        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());

        String requestString = request.toRequestString() + "\n";
        logger.trace(requestString);
        out.writeBytes(requestString);
        StringBuilder response = new StringBuilder();
        logger.trace(response.toString());

        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        clientSocket.close();
        return response.toString();
    } catch (ConnectException e) {
        throw new ApiException("SMTP mock not available at " + apiServerHostname + ":" + apiServerPort);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:org.signserver.client.cli.performance.PerformanceTestPDFServlet.java

License:asdf

/** @see org.signserver.client.PerformanceTestTask */
public boolean invoke(int threadId) {
    if (startTime == 0) {
        startTime = System.currentTimeMillis();
    }/* w  w w.jav  a 2 s .c om*/
    byte[] testPDF = pdfs
            .get((int) ((System.currentTimeMillis() - startTime) * ((long) pdfs.size()) / runTime));
    URL target;
    try {
        target = new URL(baseURLString);
        InetAddress addr = InetAddress.getByName(target.getHost());
        Socket socket = new Socket(addr, target.getPort());
        OutputStream raw = socket.getOutputStream();
        final int contentLength = REQUEST_CONTENT_WORKERNAME.length() + REQUEST_CONTENT_FILE.length()
                + testPDF.length + REQUEST_CONTENT_END.length();
        final String command = "POST " + target.getPath() + "pdf HTTP/1.0\r\n"
                + "Content-Type: multipart/form-data; boundary=signserver\r\n" + "Content-Length: "
                + contentLength + "\r\n" + "\r\n";
        raw.write(command.getBytes());
        raw.write(REQUEST_CONTENT_WORKERNAME.getBytes());
        raw.write(REQUEST_CONTENT_FILE.getBytes());
        raw.write(testPDF);
        raw.write(REQUEST_CONTENT_END.getBytes());
        raw.flush();

        InputStream in = socket.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        in.close();
        os.close();
        byte[] inbytes = os.toByteArray();

        PdfReader pdfReader = new PdfReader(inbytes);
        if (!new String(pdfReader.getPageContent(1)).contains(PDF_CONTENT)) {
            System.err.println("Did not get the same document back..");
            return false;
        }
        pdfReader.close();
        raw.close();
        socket.close();
    } catch (IOException e) {
        System.err.println("testPDF.length=" + testPDF.length + "," + e.getMessage());
        //e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.inmobi.messaging.util.GraphiteStatsEmitter.java

protected void writeStats() {
    if (null != statsExposers) {
        synchronized (statsExposers) {
            final StringBuilder lines = new StringBuilder();
            long timestamp = System.currentTimeMillis() / 1000;
            for (StatsExposer exposer : statsExposers) {
                Map<String, Number> stats = exposer.getStats();
                Map<String, String> context = exposer.getContexts();
                String topic = context.get(TopicStatsExposer.TOPIC_CONTEXT_NAME);
                /**//from  w w  w  . j a  v a  2s .  co  m
                 * Publisher will be having topic set as category in the statsexposer,
                 * but for consumers topic is set as topicName for the statsexposer.
                 */
                if (null == topic) {
                    topic = context.get(MessageConsumerMetricsConstants.TOPIC_CONTEXT);
                }
                for (Map.Entry<String, Number> entry : stats.entrySet()) {
                    lines.append(metricPrefix).append(topic).append(METRIC_SEPARATOR).append(entry.getKey());
                    lines.append(FIELD_SEPARATOR);
                    lines.append(entry.getValue().longValue());
                    lines.append(FIELD_SEPARATOR);
                    lines.append(timestamp);
                    lines.append(NEW_LINE);
                }
            }

            Socket graphiteSocket = null;
            OutputStream stream = null;
            try {
                graphiteSocket = new Socket(graphiteHost, graphitePort);
                stream = graphiteSocket.getOutputStream();
                stream.write(lines.toString().getBytes(Charset.forName("UTF-8")));
            } catch (IOException ex) {
                LOG.error("Failed to write the stats", ex);
            } finally {
                if (null != graphiteSocket && !graphiteSocket.isClosed()) {
                    try {
                        graphiteSocket.close();
                    } catch (IOException ex) {
                        LOG.warn("failure in closing the connection to graphite server", ex);
                    }
                }
                if (null != stream) {
                    try {
                        stream.close();
                    } catch (IOException ex) {
                        LOG.warn("failure in closing the input stream", ex);
                    }
                }
            }
        }
    }
}

From source file:Main.java

public InputStream getWWWPageStream(String host, String file) throws IOException, UnknownHostException {

    InetAddress webServer = InetAddress.getByName(host);

    Socket httpPipe = new Socket(webServer, 80);
    if (httpPipe == null) {
        System.out.println("Socket to Web server creation failed.");
        return null;
    }//from  w  w w .  j a va  2s  . com

    InputStream inn = httpPipe.getInputStream(); // get raw streams
    OutputStream outt = httpPipe.getOutputStream();

    DataInputStream in = new DataInputStream(inn); // turn into higher-level ones
    PrintStream out = new PrintStream(outt);

    if (inn == null || outt == null) {
        System.out.println("Failed to open streams to socket.");
        return null;
    }
    out.println("GET " + file + " HTTP/1.0\n");

    String response;
    while ((response = in.readUTF()).length() > 0) {
        System.out.println(response);
    }

    return in;
}