A Generic Client

The Connect class of Example 5-4 was a useful first example of the Socket class, but it is too simple to use with most network protocols. Example 5-5 defines a class, GenericClient, that can serve as a client for a variety of text-based services. When you run this program, it connects to the host and port you have specified on the command line. From that point on, it simply sends the text you type to the server and then outputs the text the server sends in response to the console.

You can use GenericClient to download files from a web server by sending HTTP GET commands, for example. (We’ll see what that protocol looks like in Example 5-6.) For big files, however, the server’s output scrolls by too quickly for this to be useful. GenericClient is more useful for text-based interactive protocols. The Post Office Protocol (POP) is such a protocol. You can use GenericClient to preview any email you have waiting for you at your ISP (or elsewhere). An interaction, using GenericClient, with a POP server might look as follows. The lines in bold are those typed by the user:

oxymoron% java je3.net.GenericClient mail.isp.net 110
Connected to mail.isp.net/208.99.99.251:110
+OK QUALCOMM Pop server derived from UCB (version 2.1.4-R3) at mail.isp.net
starting.
USER david
+OK Password required for david.
PASS notrealpassword
+OK david has 3 message(s) (2861 octets).
RETR 3 +OK 363 octets Received: from obsidian.oreilly.com (obsidian.oreilly.com [207.144.66.251]) by mail.isp.net ...

Get Java Examples in a Nutshell, 3rd 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.