10.6 Network Communication with Streams

Since in order to speak, one must first listen, learn to speak by listening.

—MEVLANA RUMI

We have seen that the Scanner class can be used to read data from a file or from the keyboard. Amazingly, classes such as Scanner and PrintWriter can be used with any kind of data stream! To illustrate this flexibility, here we introduce communication over a network using streams. As you will see, the code is nearly identical to reading from or writing to a file except instead the program will be reading from or sending to a computer on the Internet. This level of abstraction is made possible thanks to the principle of polymorphism discussed in Chapter 8.

When computers want to communicate ...

Get Java: An Introduction to Problem Solving and Programming, 8th Edition 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.