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

public void run() {
    try {/*w w w  .ja  v  a 2 s.  c om*/
        Socket client = serverSocket.accept();

        DataInputStream in = new DataInputStream(client.getInputStream());
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream out = new DataOutputStream(client.getOutputStream());

        while (true) {
            String message = in.readUTF();
            System.out.println(message);
            System.out.print("Enter response: ");
            String response = console.readLine();

            out.writeUTF(response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:jetbrains.exodus.util.Streamer.java

public Streamer(@NotNull Socket socket) throws IOException {
    socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()), BUFFER_SIZE);
    socketOutput = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}

From source file:MainClass.java

public void run() {
    try {/*ww  w  . j av  a  2  s .c  om*/
        Socket socket = new Socket("127.0.0.1", 2000);

        DataInputStream in = new DataInputStream(socket.getInputStream());
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());

        while (true) {
            System.out.print("Enter response: ");
            String response = console.readLine();
            out.writeUTF(response);

            String message = in.readUTF();
            System.out.println(message);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:delete.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w  w  . ja va  2  s  .  c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    Socket s = new Socket("localhost", 9999);

    DataInputStream in = new DataInputStream(s.getInputStream());
    DataOutputStream outD = new DataOutputStream(s.getOutputStream());

    outD.writeUTF(request.getParameter("employee_id"));

    in.readUTF();

    s.close();

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        out.println("Deleted");
    }
}

From source file:com.seyren.core.service.notification.IrcCatNotificationService.java

private void sendMessage(String ircCatHost, int ircCatPort, String message, String channel) throws IOException {
    Socket socket = new Socket(ircCatHost, ircCatPort);
    Closer closer = Closer.create();/*from w w w. jav  a 2 s.  c o  m*/
    try {
        Writer out = closer.register(new OutputStreamWriter(socket.getOutputStream()));
        out.write(format("%s %s\n", channel, message));
        out.flush();
    } catch (IOException e) {
        socket.close();
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:io.undertow.server.handlers.HttpTunnelingViaConnectTestCase.java

@Test
public void testConnectViaProxy() throws Exception {

    final HttpHost proxy = new HttpHost(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default") + 1, "http");
    final HttpHost target = new HttpHost(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default"), "http");
    ProxyClient proxyClient = new ProxyClient();
    Socket socket = proxyClient.tunnel(proxy, target, new UsernamePasswordCredentials("a", "b"));
    try {/*from   w w w  .  j a va 2  s.com*/
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        boolean found = false;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
            if (line.equals("MyHeader: MyValue")) {
                found = true;
            }
        }
        Assert.assertTrue(found);
    } finally {
        socket.close();
    }
}

From source file:client.communication.SocketClient.java

/**
 * Envia a mensagem para o servidor e retorna a resposta
 * //www  .j  av a  2 s. c  om
 * @param message
 * @return 
 */
public String sendMessage(String message) {
    Socket socket = null;

    PrintStream stream = null;

    try {
        socket = new Socket(serverAddress, serverPort);

        stream = new PrintStream(socket.getOutputStream());

        // Envia requisiao
        stream.println(message);

        // L resposta
        socket.getInputStream().read(response);
    } catch (IOException e) {
        System.out.println("Problem connecting server!");
    } finally {
        try {
            // Fecha stream
            if (stream != null)
                stream.close();

            if (socket != null)
                socket.close();
        } catch (IOException e) {
            System.err.println("Problem closing socket: " + e.getMessage());
        }
    }

    // Decodifica resposta em base 64
    String _reply = new String(Base64.decodeBase64(response));

    // Remove o espao nas extremidades da string de resposta
    return _reply.trim();
}

From source file:disko.flow.analyzers.socket.SocketTransmitter.java

public void writeMessage(Message message) {
    log.debug("Establishing connection to " + host + ":" + port);
    while (true) {
        Socket socket = null;
        ObjectOutputStream out = null;
        try {/*w  w  w .j  ava2 s  .  co  m*/
            socket = new Socket(host, port);
            out = new ObjectOutputStream(socket.getOutputStream());
            out.writeObject(message);
            out.flush();
            log.debug("Sent " + message);
            return;
        } catch (UnknownHostException e) {
            log.error("Error connecting to " + host + ":" + port, e);
        } catch (IOException e) {
            log.error("Error sending to " + host + ":" + port + " message " + message.getData(), e);
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (Throwable ignored) {
                    log.error("While closing transmitter output.", ignored);
                }
            if (socket != null)
                try {
                    socket.close();
                } catch (Throwable ignored) {
                    log.error("While closing transmitter socket.", ignored);

                }
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignored) {
            break;
        }
    }
}

From source file:DateServer.java

public void run() {
    while (true) {
        try {//  w  w w .java 2s.  co m
            Socket s = ss.accept();

            ObjectInputStream ois;
            ois = new ObjectInputStream(s.getInputStream());
            Locale l = (Locale) ois.readObject();

            PrintWriter pw;
            pw = new PrintWriter(s.getOutputStream());

            MessageFormat mf;
            mf = new MessageFormat("The date is {0, date, long}", l);

            Object[] args = { new Date() };

            pw.println(mf.format(args));

            pw.close();
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

From source file:gobblin.tunnel.TalkPastServer.java

@Override
void handleClientSocket(Socket clientSocket) throws IOException {
    LOG.info("Writing to client");
    try {//from  ww w  .  j  a va2s  . c  o m
        final BufferedOutputStream serverOut = new BufferedOutputStream(clientSocket.getOutputStream());
        EasyThread clientWriterThread = new EasyThread() {
            @Override
            void runQuietly() throws Exception {
                long t = System.currentTimeMillis();
                try {
                    for (int i = 0; i < nMsgs; i++) {
                        serverOut.write(generateMsgFromServer(i).getBytes());
                        sleepQuietly(2);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                LOG.info("Server done writing in " + (System.currentTimeMillis() - t) + " ms");
            }
        }.startThread();
        _threads.add(clientWriterThread);

        BufferedReader serverIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String line = serverIn.readLine();
        while (line != null && !line.equals("Goodbye")) {
            String[] tokens = line.split(":", 2);
            String client = tokens[0];
            digestMsgsRecvdAtServer.get(client).update(line.getBytes());
            digestMsgsRecvdAtServer.get(client).update("\n".getBytes());
            line = serverIn.readLine();
        }
        LOG.info("Server done reading");
        try {
            clientWriterThread.join();
        } catch (InterruptedException e) {
        }
        serverOut.write("Goodbye\n".getBytes());
        serverOut.flush();
        clientSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}