Reading and Writing Textual Data

Problem

Having connected, you wish to transfer textual data.

Solution

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

Discussion

The Socket class has methods that allow you to get an InputStream or OutputStream to read from or write to the socket. There is 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, a service 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
etwork>date 
Current date is Sun 01-23-2000 
Enter new date (mm-dd-yy):
C:javasrc
etwork>time 
Current time is  1:13:18.70p 
Enter new time:
C:javasrc
etwork>java DaytimeText darian 
Time on darian is Sun Jan 23 13:14:34 2000

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

Example 15-4. DaytimeText.java

/**
 * 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 15-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[33] for “the machine the program is running on.”

Example 15-5. EchoClientOneLine.java

/**
 * EchoClientOneLine - create client socket, send one line,
 * read it back. See also EchoClient.java, 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 
 on
            // platforms where that is the native line ending.
            os.print(mesg + "
"); 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 and the flushing.



[33] It used to be universal, when most networked systems were administered by fulltime systems people who had been trained or served an apprenticeship. Today there are so many machines on the Internet that don’t have localhost configured properly that there is a web site, http://localhost.com, which tells you about this problem if you type “localhost” into a web browser on a misconfigured machine.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.97.75