Socket I/O

Java permits a program to write to a socket, and thus send data across a network, in much the same way that it can write to a file.  And, of course, similarly for read.

To see how this is accomplished, first, review the earlier discussions on Output and Input in this lesson, paying particularly attention to the way in which components and constructed, one an another, to get instances of the desired type of writer and reader -- e.g., PrintWriter and BufferedReader.

For example, to create a PrintWriter, one first constructs a File, then uses that object to create a FileOutputStream, and, in turn, uses that to create the PrintWriter.  The key code is illustrated in the following fragment:

    try {

      File outFile = new File ( path, fileName );
      FileOutputStream outFileStream = new FileOutputStream ( outFile );
      PrintWriter outPrintWriter = new PrintWriter ( outFileStream );
      
      outPrintWriter.println ( message );
    
    }  // end try
    catch ( IOException e ) {
      System.out.println ( " I/O error: " ); 
      e.printStackTrace() );
    }  // end catch

A similar sequence is followed to build a BufferedReader, or some other desired type of reader.

To write to and read from a socket, one builds up to an object that has the desired write and read methods.  For String data coming out of a Java program that uses Unicode encoding, the preferred write and read methods are writeUTF and readUTF, contained in the DataOutputStream and DataInputStream classes, respectively.

To build these tools, one starts by creating a socket, supplying the host and port, uses that socket to create an OutputStream object, and then uses that to create a DataOutputStream object, which incluides the writeUTF method.  The key code is illustrated in the following fragment:

      
    try  {
    
      Socket socket = new Socket ( host, port );

      OutputStream outStream = socket.getOutputStream ();
      DataOutputStream outDataStream = new DataOutputStream ( outStream );
      
      outDataStream.writeUTF ( message );

    }  // end try
      catch ( IOException e)  {
      System.out.println ( " Socket I/O error: " ); 
      e.printStackTrace ();
    }  // end catch

    
A similar process is used to buildup the input tools, starting from the same socket object.

Creating read and write tools on the server side is almost identical except that one begins with a ServerSocket, instead of a plain Socket, and, second, the particular instance of the ServerSocket is normally passed to the object where the I/O is taking place from another object that is listening for connections from clients.  For details, see the lessons on Client/Servers and on Servlet Layered Architecture, particularly in the second, the ListenServer and HandleServer classes.