Reading Data with a ServerSocket

The port scanner pretty much exhausts what you can do with just the constructors. Almost all ServerSocket objects you create will use their accept() method to connect to a client.

 public Socket accept() throws IOException

There are no getInputStream() or getOutputStream() methods for ServerSocket. Instead you use accept() to return a Socket object, and then call its getInputStream() or getOutputStream() methods.

For example,

 try {
    ServerSocket ss = new ServerSocket(2345);
    Socket s = ss.accept();
    PrintWriter pw = new PrintWriter(s.getOutputStream());
    pw.println("Hello There!");
    pw.println("Goodbye now.);
    s.close();
  }
  catch (IOException ex) {
    System.err.println(ex);
  }

Notice in this example, I closed the Socket s, not the ServerSocket ss. ss is still bound to port 2345. You get a new socket for each connection but it's easy to reuse the server socket. For example, the next code fragment repeatedly accepts connections:

 try {
    ServerSocket ss = new ServerSocket(2345);
    while (true) {
      Socket s = ss.accept();
      PrintWriter pw = new PrintWriter(s.getOutputStream());
      pw.println("Hello There!");
      pw.println("Goodbye now.);
      s.close();
    }
  }
  catch (IOException ex) {
    System.err.println(ex);
  }

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified August 15, 1998