Datagram (UDP) ServerClient

 < Day Day Up > 



Datagram (UDP) Server/Client

Now, let’s look at a UDP server and client implementation using datagram sockets. Recall that datagram communication is not connection-oriented; therefore, each datagram that we send must also include the intended recipient.

Datagram Server

The datagram server is illustrated in Listing 17.3. It begins in lines 1–3 by making visible the necessary Java packages that provide the needed functionality (such as the networking classes). Next, the dgramsrv class is created, which will house the Java datagram server application (line 5). Our Java application main method follows next (line 7) as well as a set of object declarations in lines 9–11.

At line 12, we create a byte[] array of 100 bytes in length. This is done in preparation for the creation of the DatagramPacket at line 13. The DatagramPacket object is used to create datagram packets, and in this case, is created to receive the datagram from the client. When creating the new DatagramPacket object, we provide to the constructor a byte[] buffer and its length (buffer.length). This differs from the Socket and ServerSocket classes, because they are stream-oriented and deal simply with payload (recall the InputStream / OutputStream discussion). For datagrams, a special class exists to create datagram packets and to manage them.

At line 19, we create our DatagramSocket object and bind it to the local port (port). We then start our main loop to field datagram requests (line 22). The first step in our loop is to receive a datagram from a client. This is done through the receive method of the DatagramSocket, specifying the previously created DatagramPacket (line 27). The purpose of this packet was solely to identify the source of the requester, and at lines 35 and 36, we extract the source address and port using the getAddress and getPort methods on the DatagramPacket. We also create our date and time string using the Date() constructor and convert it directly to a string using the toString method. Next, we convert the string into a byte[] object using the getBytes method and store this in the buffer object. A new DatagramPacket object is then created at lines 40–43, using the new time/date buffer and length as well as the previously extracted client source address (cliadrs) and port (cliport). Finally, we send the packet back to the originator of the original datagram packet using the send method at line 48.

Listing 17.3 Java Daytime datagram server.

start example
 1   import java.net.*;  2   import java.io.*;  3   import java.util.*;  4  5   public class dgramsrv {  6  7     public static void main( String[] args ) {  8  9       String server = "localhost"; 10       int port = 13; 11       DatagramSocket socket; 12       byte[] buffer = new byte[100]; 13       DatagramPacket packet =  14              new DatagramPacket( buffer, buffer.length ); 15 16       try { 17 18         // Create the datagram server socket 19         socket = new DatagramSocket( port ); 20 21         // The big loop 22         while ( true ) { 23 24           try { 25 26             // Try to receive a datagram packet 27             socket.receive( packet ); 28 29             // Create the time/date string 30             String theDate = new Date().toString(); 31             buffer = theDate.getBytes(); 32 33             // Extract the address/port information from 34             // the incoming datagram packet. 35             InetAddress cliadrs = packet.getAddress(); 36             int cliport = packet.getPort(); 37 38             // Create a new datagram packet using the  39             // time/date string. 40             packet = new DatagramPacket( buffer,  41                                          buffer.length, 42                                          cliadrs,  43                                          cliport ); 44 45             try { 46 47               // Try to send the response packet to the client 48               socket.send( packet ); 49 50             } 51             catch( SocketException e ) 52             { 53               System.out.println( e ); 54             } 55             catch( IOException e ) 56             { 57               System.out.println( e ); 58             } 59 60           } 61           catch( IOException e ) 62           { 63             // for socket.receive 64             System.out.println( e ); 65           } 66 67         } 68 69       } 70       catch( SocketException e ) 71       { 72         // for socket creation 73         System.out.println( e ); 74       } 75 76     } 77 78   }
end example

Datagram Client

The datagram client is shown in Listing 17.4, and corresponds with the datagram server previously shown in Listing 17.3. After importing the necessary Java packages (lines 1–2), we create our class at line 4 and our main method for our Java application at line 6. Next, we create our client socket using the DatagramSocket constructor at line 15 and store our new DatagramSocket object in socket.

We create a dummy packet at lines 18–20, first allocating a byte[] array for the datagram payload and finally creating the DatagramPacket at lines 19 and 20. At line 27, we get an InetAddress object for the localhost using the getByName method of InetAddress, and store this in servaddr. We then use the setAddress method of DatagramPacket to set the destination address of the packet to the localhost (via the servaddr object) at line 30. We also set the port of the packet using the setPort method at line 31. At line 36, we send our dummy datagram to the server using the send method, which notifies it that we want to receive a response datagram containing the date and time string.

At lines 40–41, we create a new datagram packet, specifying the buffer for the receive payload. At line 43, the receive method is used to receive a DatagramPacket from the client socket. Upon receipt, the data from the packet is extracted using the getData method and anonymously passed into the String constructor to create a String object of the data. This is emitted to standard-out at line 48. Finally, the socket is closed at line 50 using the close method.

Listing 17.4 Java Daytime datagram client.

start example
 1   import java.net.*;  2   import java.io.*;  3  4   public class dgramcli {  5  6     public static void main( String[] args ) {  7  8       String server = "localhost";  9       int port = 13; 10       DatagramSocket socket; 11 12       try { 13 14         // Create a new client socket 15         socket = new DatagramSocket(); 16 17         // Create a dummy packet 18         byte[] buf = new byte[100]; 19         DatagramPacket packet =  20             new DatagramPacket( buf, 0 ); 21 22         InetAddress servaddr; 23 24         try { 25 26           // Get the address of the current host  27           servaddr = InetAddress.getByName( server ); 28 29           // Set the packets destination port and address 30           packet.setAddress( servaddr ); 31           packet.setPort( port ); 32 33           try { 34 35             // Send the packet to the server 36             socket.send( packet ); 37 38             // Await the response packet and then print 39             // the contents (the time string). 40             packet =  41               new DatagramPacket( buf, buf.length ); 42 43             socket.receive( packet ); 44 45             String received =  46               new String( packet.getData() ); 47 48             System.out.println( received ); 49 50             socket.close(); 51 52           } 53           catch( SocketException e ) 54           { 55             System.out.println( e ); 56           } 57           catch( IOException e ) 58           { 59             System.out.println( e ); 60           } 61 62         } 63         catch( UnknownHostException e ) 64         { 65           System.out.println( e ); 66         } 67 68       } 69       catch( SocketException e ) 70       { 71         System.out.println( e ); 72       } 73 74     } 75 76   }
end example



 < 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