A Simple Network Client

Example 5-4 is a simple network client program that does not use the URL class. Instead, it uses java.net.Socket to connect to server. It sends a line of text to the server, and then reads and prints out the server’s response. The main point of interest in this example is the introduction of the Socket class, which creates a stream-based network connection between a client and a server. To create a network connection to another host, you simply create a Socket, specifying the desired host and port. If there is a program (a server) running on the specified host and listening for connections on the specified port, the Socket( ) constructor returns a Socket object you can use to communicate with the server. (If there is not a server listening on the specified host and port, or if anything goes wrong—and many things can go wrong with networking—the Socket( ) constructor throws an exception.)

If you are not familiar with hosts and ports, think of the host as a post office and the port as a post-office box. Just as a post office has many different post-office boxes, any host on the network can run many different servers at a time. Different servers use different ports for their addresses. To establish a connection, you must specify both the correct host and the correct port. Many services have standard default ports. Web servers run on port 80, POP email servers run on port 110, and so on.

Once you have a Socket object, you are connected, across the network, ...

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.