Recipe 16.4 Reading and Writing Textual Data


Having connected, you wish to transfer textual data.


Construct a BufferedReader or PrintWriter from the socket's getInputStream( ) or getOutputStream( ).


The Socket class has methods that allow you to get an InputStream or OutputStream to read from or write to the socket. It has no method to fetch a Reader or Writer, partly because some network services are limited to ASCII, but mainly because the Socket class was decided on before there were Reader and Writer classes. You can always create a Reader from an InputStream or a Writer from an OutputStream using the conversion classes. The paradigm for the two most common forms is:

BufferedReader is = new BufferedReader(     new InputStreamReader(sock.getInputStream( ))); PrintWriter os = new PrintWriter(sock.getOutputStream( ), true);

Here is code that reads a line of text from the "daytime" service, which is offered by full-fledged TCP/IP suites (such as those included with most Unixes). You don't have to send anything to the Daytime server; you simply connect and read one line. The server writes one line containing the date and time and then closes the connection.

Running it looks like this. I started by getting the current date and time on the local host, then ran the DaytimeText program to see the date and time on the server (machine darian is my local server):

C:\javasrc\network>date  Current date is Sun 01-23-2000  Enter new date (mm-dd-yy): C:\javasrc\network>time  Current time is  1:13:18.70p  Enter new time: C:\javasrc\network>java DaytimeText darian  Time on darian is Sun Jan 23 13:14:34 2000

The code is in class DaytimeText , shown in Example 16-4.

Example 16-4.
/**  * DaytimeText - connect to the Daytime (ascii) service.  */ public class DaytimeText {     public static final short TIME_PORT = 13;     public static void main(String[] argv) {         String hostName;         if (argv.length == 0)             hostName = "localhost";         else             hostName = argv[0];         try {             Socket sock = new Socket(hostName, TIME_PORT);             BufferedReader is = new BufferedReader(new                  InputStreamReader(sock.getInputStream( )));             String remoteTime = is.readLine( );             System.out.println("Time on " + hostName + " is " + remoteTime);         } catch (IOException e) {             System.err.println(e);         }     } }

The second example, shown in Example 16-5, shows both reading and writing on the same socket. The Echo server simply echoes back whatever lines of text you send it. It's not a very clever server, but it is a useful one. It helps in network testing and also in testing clients of this type!

The converse( ) method holds a short conversation with the Echo server on the named host; if no host is named, it tries to contact localhost, a universal alias[2] for "the machine the program is running on."

[2] It used to be universal, when most networked systems were administered by full-time systems people who had been trained or served an apprenticeship. Today many machines on the Internet don't have localhost configured properly.

Example 16-5.
/**  * EchoClientOneLine - create client socket, send one line,  * read it back. See also, slightly fancier.  */ public class EchoClientOneLine {     /** What we send across the net */     String mesg = "Hello across the net";     public static void main(String[] argv) {         if (argv.length == 0)             new EchoClientOneLine( ).converse("localhost");         else             new EchoClientOneLine( ).converse(argv[0]);     }     /** Hold one conversation across the net */     protected void converse(String hostName) {         try {             Socket sock = new Socket(hostName, 7); // echo server.             BufferedReader is = new BufferedReader(new                  InputStreamReader(sock.getInputStream( )));             PrintWriter os = new PrintWriter(sock.getOutputStream( ), true);             // Do the CRLF ourself since println appends only a \r on             // platforms where that is the native line ending.             os.print(mesg + "\r\n"); os.flush( );             String reply = is.readLine( );             System.out.println("Sent \"" + mesg  + "\"");             System.out.println("Got  \"" + reply + "\"");         } catch (IOException e) {             System.err.println(e);         }     } }

It might be a good exercise to isolate the reading and writing code from this method into a NetWriter class, possibly subclassing PrintWriter and adding the \r\n and the flushing.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: