5. Establish a TCP client
After discussing the functions of the socket class, we will analyze a complete TCP client program. The client program we will see here is a daytime client that connects to a daytime server program to read the current date and time. Establishing a socket connection and reading information is a simple process, requiring only a small amount of code.
By default, the daytime service runs on Port 13. Not every computer runs the daytime server program, but the Unix Server is a good system running on the client. If you do not have the permission to access the Unix server, we provide the TCP daytime server program code in section 7-with this code client, you can run it.
DaytimeClient code Import java.net .* Import java. io .*; Public class DaytimeClient { Public static final int SERVICE_PORT = 13; Public static void main (String args []) { // Check host name Parameters If (args. length! = 1) { System. out. println ("Syntax-DaytimeClient host "); Return; } // Obtain the Host Name of the server program String hostname = args [0]; Try { // Obtain a socket connected to the daytime Service Socket daytime = new Socket (hostname, SERVICE_PORT ); System. out. println ("Connection established "); // Set the socket option when the server program is stopped Daytime. setSoTimeout (2000 ); // Read information from the server program BufferedReader reader = new BufferedReader ( New InputStreamReader (Daytime. getInputStream () )); System. out. println ("Results:" + Reader. readLine ()); // Close the connection Daytime. close (); } Catch (IOException ioe) { System. err. println ("Error" + ioe ); } } } |
How DaytimeClient works
The Daytime application is easy to understand and uses the concepts mentioned above. Establish a socket and obtain the input stream. In a few events, the server program that is as simple as daytime fails during connection.) activate the timeout setting. Instead of connecting filtered streams, a buffer reader is connected to the socket input stream and the result is displayed to the user. Finally, the client terminates after the socket connection is closed. This is the simplest Socket Application you may get-complexity comes from the implemented network protocol, rather than programming from a specific network.
Run DaytimeClient
Running the above application is simple. Simply specify and run the Host Name of the computer running the daytime service as the command line parameter. If the daytime server program uses a non-standard port number, we will discuss it later), remember to change the port number and recompile it.
For example, if the server program is on the local machine, the following command is used to run the client: