19.1 ESTABLISHING SOCKET CONNECTIONS WITH EXISTING SERVERS IN JAVA


19.1 ESTABLISHING SOCKET CONNECTIONS WITH EXISTING SERVERS IN JAVA

The following program is a client that seeks to connect to a server on port 80.[1] This port is usually monitored by the HTTPD servers (the HyperText Transmission Protocol Daemon program) on machines on which such servers are installed and running. In response to an appropriately formatted "GET" request received from a client on port 80, an HTTPD server can send back a web page whose URL is embedded in the request. Let's see how this can be done.

A client wishing to receive web pages from an HTTPD server that monitors port 80 constructs a socket by

     Socket t = new Socket( webAddress, 80 ); 

The class Socket is defined in the package java.net. For example, if we wanted to download the raw ascii of the Purdue University web page, we would use the invocation

      Socket socket = new Socket( "www.purdue.edu", 80 ); 

in our client program.[2] The Socket object thus constructed talks to the http://www.purdue.edu server on port 80 and delivers to it the client's "socket number," which consists of the IP address of the client and the port number being used by the client. The server acknowledges this request by sending back its own socket number, which is a concatenation of the IP address of the server and the port number the server will use for the connection with the client. The socket constructor throws the UnknownHostException if it is not able to establish a connection with the server.

Once a client has established a socket link with the server, the data can be sent to the server and received back from the server on the link using essentially the same methods that are used for reading from files and writing into files on a local machine. The Socket class has two methods, getInputStream and getOutputStream, that return InputStream and OutputStream objects, respectively. Of course, when possible, for convenience you would want to convert the bin I/O stream objects into character I/O stream objects of type Reader and Writer.

      OutputStream out = socket.getOutputStream();      PrintStream ps = new PrintStream( out, true );      InputStream in = socket.getInputStream();      InputStreamReader in_reader = new InputStreamReader( in );      BufferedReader br = new BufferedReader( in_reader ); 

The Reader object in_reader turns the bytes output by the InputStream object in into Unicode characters. By feeding these into the BufferedReader object br, we can invoke the efficient readLine method of BufferedReader to input one line of text at a time.

There is one more thing that needs to be mentioned in order to extract the raw ascii of a web page through a client socket. After establishing the socket communication link, the HTTPD server needs a precisely formatted request for the page. The format of this request is

      GET http://....web-address... /HTTP/1.1\n\n         <------ 256 chars -----> 

where by web-address we mean a string such as http://www.purdue.edu This string must be 256 characters long, with spaces occupying the positions not needed by the web address. In the following example, we synthesize this request in the char array urlArr.

 
//ClientSocket.java import java.io.*; import java.net.*; class ClientSocket { public static void main( String[] args ) { try { char[] urlArr = new char[256]; String prefix = "http://"; String webAddress = args[0]; int i = 0; while ( i < prefix.length() ) { urlArr[ i ] = prefix.charAt( i ); i++; } while ( i < ( webAddress.length() + prefix.length() ) ) { urlArr[i] = webAddress.charAt( i - prefix.length() ); i++; } while ( i < 256 ) { urlArr[ i ] = ' '; i++; } String urlString = new String( urlArr ); Socket socket = new Socket( webAddress, 80 ); OutputStream os = socket.getOutputStream(); PrintStream ps = new PrintStream( os, true ); InputStream in = socket.getInputStream(); InputStreamReader in_reader = new InputStreamReader( in ); BufferedReader b_reader = new BufferedReader( in_reader ); //format of GET request dictated by HTTP ps.print( "GET" + urlString + " /HTTP/1.1\n\n" ); boolean more = true; while (more) { String str = b_reader.readLine(); if (str == null) more = false; else System. out.println(str); } } catch( IOException e ) { System.out.println( "Error: " + e ); } } }

When this program is executed by the call

    java ClientSocket www.purdue.edu 

the following is printed out on your screen:

     HTTP/1.1 200 OK     Date: Mon, 03 Jan 2000 05:49:15 GMT     Server: Apache/1.3.9 (Unix)     Connection: close     Content-Type: text/html     <html>     <head>     <title>Purdue University - West Lafayette, Indiana</title>     <meta name=''keywords'' content=''Purdue University, Boilermakers, Boilers, \     College, higher education, West Lafayette, Indiana, public schools, United \     States, academics, research, athletics, employment, professors, faculty, \     technology, libraries, Ross-Ade Stadium, Mackey Arena, students, airport''>     <meta name=''AUTHOR'' content=''Rick DeLucio, Office of Publications, \     Purdue University''>     <meta name=''ROBOTS'' content=''ALL''>     <meta name=''DESCRIPTION'' content=''This isthe official website of Purdue \     University. It contains all known relevant information concerning the      \     university, the faculty, staff, and students.''>     <style type=''text/css''>     >!--     .roll { color: black; text-decoration: underline; text-transform: none;    \     letter-spacing: normal }     a.roll:hover { color: gray }-->     </style>     <BASE HREF=''http://www.purdue.edu/Purdue/''>     </head>     <body bgcolor=''white'' link=''black'' vlink=''#666666'' alink#''#ce9c00''>     ..........     .......... 

Not all servers require that a client socket send them a specially formatted request in order to yield information. For example, if you construct a socket object in your program by connecting with port 13 of the "time-of-day" server maintained by the National Institute of Standards and Technology in Boulder, Colorado, by

     Socket socket = new Socket( "time-A.timefreq.bldrdoc.gov", 13 ); 

you can get the time information directly by reading off the output stream as in the above program.

[1]All communication in client-Server links takes place through ports. The port numbers 0 through 255 are reserved for standard network services such as TELNET,FTP,FINGER,TFTP,ECHO, and so on. Port numbers above 255 can be used for more specialized user-Created services.

[2]The Socket constructor call shown here is for establishing communication with a server using what's referred to as "a reliable, connection-based stream protocol," as in TCP (forTransmission Control Protocol). By appropriate handshaking with the destination machine, TCP ensures that a packet sent over a network was actually received at the destination. If the data was not received, it is re-transmitted. TCP is used by higher-level utility protocols such as Telnet, FTP (for File Transfer Protocol), SMTP (Simple Mail Transfer Protocol), rlogin (for remote log in), and so on. One can also construct a socket object that would permit communication based on the less reliable but faster datagram protocol, as used in UDP (for User Datagram Protocol). UDP is used by Trivial File Transfer Protocol (TFTP), the Remote Call Procedure (RCP), and so on. UDP is particularly suitable for those applications where missing packets can be tolerated, as for example in audio and video transmissions.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

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