Chapter: Java The Complete Reference - The Java Library - Networking

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Datagrams - Java Networking

TCP/IP-style networking is appropriate for most networking needs. It provides a serialized, predictable, reliable stream of packet data.

Datagrams

 

TCP/IP-style networking is appropriate for most networking needs. It provides a serialized, predictable, reliable stream of packet data. This is not without its cost, however. TCP includes many complicated algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to a somewhat inefficient way to transport data. Datagrams provide an alternative.

Datagrams are bundles of information passed between machines. They are somewhat like a hard throw from a well-trained but blindfolded catcher to the third baseman. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it. Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a response.

 

Java implements datagrams on top of the UDP protocol by using two classes: the DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or receive the DatagramPackets. Each is examined here.

 

DatagramSocket

 

DatagramSocket defines four public constructors. They are shown here: DatagramSocket( ) throws SocketException

DatagramSocket(int port) throws SocketException

 

DatagramSocket(int port, InetAddress ipAddress) throws SocketException DatagramSocket(SocketAddress address) throws SocketException

 

The first creates a DatagramSocket bound to any unused port on the local computer. The second creates a DatagramSocket bound to the port specified by port. The third constructs a DatagramSocket bound to the specified port and InetAddress. The fourth constructs a

DatagramSocket bound to the specified SocketAddress. SocketAddress is an abstract class that is implemented by the concrete class InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number. All can throw a SocketException if an error occurs while creating the socket.

DatagramSocket defines many methods. Two of the most important are send( ) and receive( ), which are shown here:

 

void send(DatagramPacket packet) throws IOException void receive(DatagramPacket packet) throws IOException

 

The send( ) method sends a packet to the port specified by packet. The receive( ) method waits for a packet to be received and returns the result.

DatagramSocket also defines the close( )method, which closes the socket. Beginning with JDK 7, DatagramSocket implements AutoCloseable, which means that a DatagramSocket can be managed by a try-with-resources block.

Other methods give you access to various attributes associated with a DatagramSocket. Here is a sampling:



InetAddress getInetAddress( ) : If the socket is connected, then the address is returned. Otherwise, null is returned.

 

int getLocalPort( ) : Returns the number of the local port.

 

int getPort( ) : Returns the number of the port to which the socket is connected. It returns –1 if the socket is not connected to a port.

 

boolean isBound( ) : Returns true if the socket is bound to an address. Returns false otherwise.

 

boolean isConnected( ) : Returns true if the socket is connected to a server. Returns false otherwise.

 

void setSoTimeout(int millis) throws SocketException : Sets the time-out period to the number of milliseconds passed in millis.

DatagramPacket

 

DatagramPacket defines several constructors. Four are shown here:

 

DatagramPacket(byte data [ ], int size) DatagramPacket(byte data [ ], int offset, int size)

DatagramPacket(byte data [ ], int size, InetAddress ipAddress, int port) DatagramPacket(byte data [ ], int offset, int size, InetAddress ipAddress, int port)

 

The first constructor specifies a buffer that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket. The second form allows you to specify an offset into the buffer at which data will be stored. The third form specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent. The fourth form transmits packets beginning at the specified offset into the data. Think of the first two forms as building an "in box," and the second two forms as stuffing and addressing an envelope.

DatagramPacket defines several methods, including those shown here, that give access to the address and port number of a packet, as well as the raw data and its length.


 

InetAddress getAddress( ) : Returns the address of the source (for datagrams being received) or destination (for datagrams being sent).

 

byte[ ] getData( ) : Returns the byte array of data contained in the datagram. Mostly used to retrieve data from the datagram after it has been received.

 

int getLength( ) : Returns the length of the valid data contained in the byte array that would be returned from the getData( ) method. This may not equal the length of the whole byte array.

 

int getOffset( ) : Returns the starting index of the data.

 

int getPort( ) : Returns the port number.

 

void setAddress(InetAddress ipAddress) : Sets the address to which a packet will be sent. The address is specified by ipAddress.

 

void setData(byte[ ] data) : Sets the data to data, the offset to zero, and the length to number of bytes in data.

 

void setData(byte[ ] data, int idx, int size) : Sets the data to data, the offset to idx, and the length to size.

 

void setLength(int size) : Sets the length of the packet to size.

 

void setPort(int port) : Sets the port to port.

A Datagram Example

 

The following example implements a very simple networked communications client and server. Messages are typed into the window at the server and written across the network to the client side, where they are displayed.

 

// Demonstrate datagrams.

 

 import java.net.*;

 

class WriteServer {

 

public static int serverPort = 998; public static int clientPort = 999; public static int buffer_size = 1024; public static DatagramSocket ds;

 

public static byte buffer[] = new byte[buffer_size];

 

public static void TheServer() throws Exception { int pos=0;

 

while (true) {

 

int c = System.in.read(); switch (c) {

case -1:

System.out.println("Server Quits.");

 ds.close();

 

return; case '\r': break; case '\n':

 

ds.send(new

DatagramPacket(buffer,pos, InetAddress.getLocalHost(),clientPort));

 

pos=0;

 

break;

 

default:

 

buffer[pos++] = (byte) c;

 

}

 

}

 

}

 

public static void TheClient() throws Exception { while(true) {

 

DatagramPacket p = new DatagramPacket(buffer, buffer.length); ds.receive(p);

 

System.out.println(new String(p.getData(), 0, p.getLength()));

 

}

 

}

 

public static void main(String args[]) throws Exception { if(args.length == 1) {

 

ds = new DatagramSocket(serverPort); TheServer();

} else {

 

ds = new DatagramSocket(clientPort); TheClient();

}

 

}

 

}

 

This sample program is restricted by the DatagramSocket constructor to running between two ports on the local machine. To use the program, run

 

java WriteServer

 

in one window; this will be the client. Then run

 

java WriteServer 1

 

This will be the server. Anything that is typed in the server window will be sent to the client window after a newline is received.

 


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.