Writing Output to a Socket

The getOutputStream() method returns an OutputStream which writes data to the socket. You can use all the normal methods of the OutputStream class you learned about in Week 10 to read this data. Most of the time you'll want to chain the raw OutputStream to some other output stream or writer class to more easily handle the data.

For example, the following program connects to the discard server on port 9 of metalab.unc.edu, and sends it data read from System.in.

    byte[] b = new byte[128];
    try {
      Socket s = new Socket("metalab.unc.edu", 9);
      OutputStream out = s.getOutputStream();
      while (true) {
        int m = System.in.read(b, 0, b.length);
        if (m == -1) break;
        out.write(b, 0, m);
    catch (IOException ex) {

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999, 2003 Elliotte Rusty Harold
Last Modified May 6, 2003