Stream (TCP) ServerClient

 < Day Day Up > 



Stream (TCP) Server/Client

The stream server and client demonstrate the Daytime protocol using stream sockets (reliable TCP-based communication).

Stream Server

The Daytime protocol stream server is shown in Listing 17.1. The first item to note is the importing of a number of Java packages that provide the necessary networking and I/O functionality. The import statement is Java’s way of identifying the needed external resource classes that will be used (lines 1–3). Next, we create a public class (strmsrv) to contain our Java application (line 5). The main method shown is the entry point for the application when started. The main acts like a standard C main, and accepts a number of arguments, though none are used here. Although only an argument list is shown passed here in main, the number of arguments can be retrieved using the length attribute of the args object (args.length). After the declaration of the main method of the strmsrv class, a number of declarations are made (lines 9–13). Rather than discuss them here (because most are self-explanatory), we discuss each as they are utilized in the application.

As in other TCP server applications, we use the ServerSocket constructor to create a new ServerSocket object (line 18). We pass in our port number variable, so that our new server will be bound to port 13. Next, we enter the server loop to await incoming client connections (line 20). The accept method is used to accept new connections (line 23), for which we store the new Socket object in clisock (our client socket object). We don’t intend to read any data from our client socket, but we do intend to write the date and time string, so we create a PrintWriter stream over the socket (lines 28–30). We use the getOutputStream method on our client socket to get the OutputStream and then pass this anonymously to the PrintWriter constructor to create our PrintWriter object (output). Recall that the second argument (true) is the auto-flush specifier.

Now that we can write simply through our client socket, we create the date and time string (lines 33–34). We use the Date() constructor to create a Date object, and then convert this to a string with the toString method. Finally, at line 37, we use the println method of the PrintWriter object to write the date and time string to the socket through the PrintWriter stream. We can then close the socket using the close method (at line 41).

Listing 17.1 Java Daytime stream server.

start example
 1   import java.net.*;  2   import java.io.*;  3   import java.util.*;  4  5   public class strmsrv {  6  7     public static void main( String[] args ) {  8  9       int port = 13; 10       String line; 11       ServerSocket servsock; 12       Socket clisock; 13       PrintWriter output; 14 15       try { 16 17         // Create a new Server socket 18         servsock = new ServerSocket( port ); 19 20         while ( true ) { 21 22           // Await a client connection 23           clisock = servsock.accept(); 24 25           try { 26 27             // Create a new PrintWriter for output 28             output = new  29                PrintWriter( clisock.getOutputStream(), 30                             true ); 31 32             // Generate a time string 33             Date now = new Date(); 34             String curtime = now.toString(); 35 36             // Write the time out to the socket 37             output.println( curtime ); 38 39             // Try to close the socket 40             try { 41               clisock.close(); 42             } 43             catch( IOException e ) { 44               System.out.println( e ); 45             } 46 47           } 48           catch( IOException e ) { 49             System.out.println( e ); 50           } 51 52         } 53 54       } 55       catch ( UnknownHostException e ) { 56         System.out.println( e ); 57         System.exit( -1 ); 58       } 59       catch ( IOException e ) { 60         System.out.println( e ); 61         System.exit( -1 ); 62       } 63 64     } 65 66   }
end example

Stream Client

Now, let’s look at the Daytime stream client (shown in Listing 17.2). The client creates a socket to connect to the server and then awaits a string to be received through the socket. Upon receiving the string from the server, the message is printed and the client exits.

Listing 17.2 Java Daytime stream client.

start example
 1   import java.net.*;  2   import java.io.*;  3  4   public class strmcli {  5  6     public static void main( String[] args ) {  7  8       int port = 13;  9       String server = "localhost"; 10       String line; 11       Socket socket; 12       BufferedReader input; 13 14       try { 15 16         // Create a new client socket 17         socket = new Socket( server, port ); 18         System.out.println( "Connected to " +  19                              socket.getInetAddress() + 20                              " : " + socket.getPort() ); 21 22         try { 23 24           // Build a BufferedReader input stream from  25           // the socket 26           input = new BufferedReader(  27                     new InputStreamReader(  28                           socket.getInputStream() ) ); 29 30           // Get a line from the socket and then print it 31           line = input.readLine(); 32           System.out.println( line ); 33 34           // Try to close the socket 35           try { 36             socket.close(); 37           } 38           catch( IOException e ) { 39             System.out.println( e ); 40           } 41 42         } 43         catch ( IOException e ) { 44           System.out.println( e ); 45         } 46 47       } 48       catch ( UnknownHostException e ) { 49         System.out.println( e ); 50         System.exit( -1 ); 51       } 52       catch ( IOException e ) { 53         System.out.println( e ); 54         System.exit( -1 ); 55       } 56 57     } 58 59   }
end example

We begin by making the java.net and java.io package classes available using the import statement in lines 1–2. Next, we create our strmcli class (line 4) and create our application’s main method at line 6. A number of variable declarations are made at lines 8–12; we discuss each as they arise in the application.

We create our client socket at line 17 using the Socket constructor of the Socket class. We specify the server and port in the Socket constructor and upon completion of this method, we are connected to the server. We follow socket creation with a simple debug showing the IP address and port number to which we’re connected (the remote server) using the getInetAddress and getPort methods of our client socket.

In order to read from the socket, we create another layered stream to simplify the process (lines 26–28). We first get the InputStream of our client socket and anonymously pass this to the InputStreamReader constructor to create a new InputStreamReader object. This in turn is passed anonymously to the BufferedReader constructor providing us with a BufferedReader object (called input). We use the readLine method of our BufferedReader object to get a line from the socket and then emit it to standard-out using the println method. Finally, we close the socket at line 36 using the close method.



 < Day Day Up > 



BSD Sockets Programming from a Multi-Language Perspective
Network Programming for Microsoft Windows , Second Edition (Microsoft Programming Series)
ISBN: 1584502681
EAN: 2147483647
Year: 2003
Pages: 225
Authors: Jim Ohlund

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