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\network>date Current date is Sun 01-23-2000 Enter new date (mm-dd-yy): C:\javasrc\network>time ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.