Reading Input from a Socket

Once a socket has connected you send data to the server via an output stream. You receive data from the server via an input stream. Exactly what the data you send and receive means often depends on the protocol.

The getInputStream() method returns an InputStream which reads data from the socket. You can use all the normal methods of the InputStream class you learned about in Week 10 to read this data. Most of the time you'll want to chain the InputStream to some other input stream or reader class to more easily handle the data.

For example, the following code fragment connects to the daytime server on port 13 of, and displays the data it sends.

   try {
      Socket s = new Socket("", 13);
      InputStream is = s.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String theTime = br.readLine();
    catch (IOException ex) {
      return (new Date()).toString();

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
Last Modified December 28, 1997