Connecting to a Server


Before writing our first network program, let's learn about a great debugging tool for network programming that you already have, namely, telnet. Telnet is preinstalled on most systems (both UNIX and Windows). You should be able to launch it by typing telnet from a command shell.

You may have used telnet to connect to a remote computer, but you can use it to communicate with other services provided by Internet hosts as well. Here is an example of what you can do. Type

 telnet time-A.timefreq.bldrdoc.gov 13 

As Figure 3-1 shows, you should get back a line like this:

 53221 04-08-04 02:19:40 50 0 0 513.0 UTC(NIST) * 

Figure 3-1. Output of the "time of day" service


What is going on? You have connected to the "time of day" service that most UNIX machines constantly run. The particular server that you connected to is operated by the National Institute of Standards and Technology in Boulder, Colorado, and gives the measurement of a Cesium atomic clock. (Of course, the reported time is not completely accurate due to network delays.)

By convention, the "time of day" service is always attached to "port" number 13.

NOTE

In network parlance, a port is not a physical device, but an abstraction to facilitate communication between a server and a client (see Figure 3-2).

Figure 3-2. A client connecting to a server port



The server software is continuously running on the remote machine, waiting for any network traffic that wants to chat with port 13. When the operating system on the remote computer receives a network package that contains a request to connect to port number 13, it wakes up the listening server process and establishes the connection. The connection stays up until it is terminated by one of the parties.

When you began the telnet session with time-A.timefreq.bldrdoc.gov at port 13, an unrelated piece of network software knew enough to convert the string "time-A.timefreq.bldrdoc.gov" to its correct Internet Protocol address, 132.163.4.104. The software then sent a connection request to that computer, asking for a connection to port 13. Once the connection was established, the remote program sent back a line of data and then closed the connection. In general, of course, clients and servers engage in a more extensive dialog before one or the other closes the connection.

Here is another experiment, along the same lines, that is a bit more interesting. Do the following:

1.

Use telnet to connect to java.sun.com on port 80.

2.

Type the following, exactly as it appears, without pressing backspace. Note that there are spaces around the first slash but not the second.

3.

GET / HTTP/1.0

4.

Now, press the ENTER key two times.

Figure 3-3 shows the response. It should look eerily familiaryou got a page of HTML-formatted text, namely, the main web page for Java technology.

Figure 3-3. Using telnet to access an HTTP port


This is exactly the same process that your web browser goes through to get a web page. The only difference is that the browser displays the HTML code with nicer fonts.

Our first network program in Example 3-1 will do the same thing we did using telnetconnect to a port and print out what it finds.

Example 3-1. SocketTest.java
  1. import java.io.*;  2. import java.net.*;  3. import java.util.*;  4.  5. /**  6.    This program makes a socket connection to the atomic clock  7.    in Boulder, Colorado, and prints the time that the  8.    server sends.  9. */ 10. public class SocketTest 11. { 12.    public static void main(String[] args) 13.    { 14.       try 15.       { 16.          Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); 17.          try 18.          { 19.             InputStream inStream = s.getInputStream(); 20.             Scanner in = new Scanner(inStream); 21. 22.             while (in.hasNextLine()) 23.             { 24.                String line = in.nextLine(); 25.                System.out.println(line); 26.             } 27.          } 28.          finally 29.          { 30.             s.close(); 31.          } 32.       } 33.       catch (IOException e) 34.       { 35.          e.printStackTrace(); 36.       } 37.    } 38. } 

The key statements of this simple program are as follows:

 Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); InputStream inStream = s.getInputStream(); 

The first line opens a socket, which is an abstraction for the network software that enables communication out of and into this program. We pass the remote address and the port number to the socket constructor. If the connection fails, then an UnknownHostException is thrown. If there is another problem, then an IOException occurs. Because UnknownHostException is a subclass of IOException and this is a sample program, we just catch the superclass.

Once the socket is open, the getInputStream method in java.net.Socket returns an InputStream object that you can use just like any other stream. (See Volume 1, Chapter 12 for information about streams.) Once you have grabbed the stream, this program simply:

  1. Uses a Scanner to read a line of characters sent by the server; and

  2. Prints each line out to standard output.

This process continues until the stream is finished and the server disconnects.

NOTE

This program works only with very simple servers, such as a "time of day" service. In more complex networking programs, the client sends request data to the server, and the server may not immediately disconnect at the end of a response. You will see how to implement that behavior in several examples throughout this chapter.


The Socket class is pleasant and easy to use because Java technology hides the complexities of establishing a networking connection and sending data across it. The java.net package essentially gives you the same programming interface you would use to work with a file.


 java.net.Socket 1.0 

  • Socket(String host, int port)

    constructs a socket to connect to the given host and port.

  • InputStream getInputStream()

  • OutputStream getOutputStream()

    get streams to read data from the socket and write data to the socket.



    Core JavaT 2 Volume II - Advanced Features
    Building an On Demand Computing Environment with IBM: How to Optimize Your Current Infrastructure for Today and Tomorrow (MaxFacts Guidebook series)
    ISBN: 193164411X
    EAN: 2147483647
    Year: 2003
    Pages: 156
    Authors: Jim Hoskins

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net