Computer networks -- 2008-2009 -- info.uvt.ro/Sockets/UDP/Examples/MOTD

From Wikiversity

Quick links: front; agenda; courses 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13; examination.

Important! Please note that the current work serves mainly as general guidance and discussion topics, and is by no means the reference material for the course. For further information please consult the dedicated section.

Client[edit]

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


public class MotdClient
{
	public static void main (String[] arguments)
	{
		if (arguments.length != 1) {
			System.err.println ("wrong arguments !!!");
			return;
		}
		
		// Selecting the arguments.
		String broadcastPortAsString = arguments[0];
		
		// Parsing the server port.
		int broadcastPort;
		try {
			broadcastPort = Integer.parseInt (broadcastPortAsString);
		} catch (NumberFormatException exception) {
			System.err.println ("wrong broadcast port !!!");
			return;
		}
		
		// Creating and binding the socket.
		DatagramSocket socket;
		try {
			System.err.println ("creating and binding socket...");
			socket = new DatagramSocket (broadcastPort);
		} catch (SocketException exception) {
			// An unknown / unexpected network error was encountered. (Not a normal situation.)
			exception.printStackTrace (System.err);
			return;
		}
		
		// Only for debugging purposes.
		// Obtaining and printing the local socket address (the datagram source). (Which should be an instance of InetSocketAddress.)
		InetSocketAddress localSocketAddress = (InetSocketAddress) socket.getLocalSocketAddress ();
		System.err.println ("local socket address -->");
		printInetSocketAddress (localSocketAddress);
		
		// Setting a maximum datagram backing buffer size.
		int datagramBufferSize = 2048;
		
		// Creating the datagram backing buffer.
		byte[] datagramBuffer = new byte [datagramBufferSize];
		int datagramBufferOffset = 0;
		
		// Creating the datagram.
		DatagramPacket datagram = new DatagramPacket (datagramBuffer, datagramBufferOffset, datagramBufferSize);
		
		// Setting a loop counter.
		int counter = 10;
		
		// Loop
		while (counter > 0) {
			
			// Receiving a datagram.
			try {
				System.err.println ("receiving datagram...");
				socket.receive (datagram);
			} catch (IOException exception) {
				// An unknown / unexpected network error was encountered. (Not a normal situation.)
				exception.printStackTrace (System.err);
				return;
			}
			
			// Obtaining the datagram source address. (Which should be an instance of InetSocketAddress.)
			InetSocketAddress datagramSource = (InetSocketAddress) datagram.getSocketAddress ();
			
			// Only for debugging purposes.
			// Printing the datagram source address.
			System.err.println ("datagram source -->");
			printInetSocketAddress (datagramSource);
			
			// Obtaining the datagram actual length (how much data was received, or how much of the backing buffer was used).
			int datagramBufferUsed = datagram.getLength ();
			
			// Decoding the message (which should be a string).
			String message = new String (datagramBuffer, datagramBufferOffset, datagramBufferUsed);
			
			System.err.println ("received -->");
			System.err.println ("    message = " + message);
			
			counter--;
		}
		
		// Closing the socket.
		System.err.println ("closing socket...");
		socket.close ();
	}
	
	public static void printInetSocketAddress (InetSocketAddress socketAddress)
	{
		// Obtaining the local IP address.
		InetAddress address = socketAddress.getAddress ();
		
		// Obtaining the local port.
		int port = socketAddress.getPort ();
		
		// Printing obtained information;
		printInetAddress (address);
		System.err.println ("    port = " + port);
	}
	
	public static void printInetAddress (InetAddress address)
	{
		// Obtaining the IP as a string.
		String ipAsString = address.getHostAddress ();
		
		// Obtaining the IP as an array of bytes.
		byte[] ipAsBytes = address.getAddress ();
		
		// Obtaining the reverse host name.
		String reverseName = address.getCanonicalHostName ();
		
		// Printing the default string representation.
		System.err.println ("    address = " + address);
		
		// Printing the IP as string.
		System.err.println ("    ip as string = " + ipAsString);
		
		// Printing the IP as bytes.
		System.err.println ("    ip as bytes length = " + ipAsBytes.length);
		System.err.print ("    ip as bytes =");
		for (byte b : ipAsBytes)
			System.err.print (" " + (b));
		System.err.println ();
		
		// Printing the reverse host name.
		System.err.println ("    reverse name = " + reverseName);
	}
}

Server[edit]

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MotdServer
{
	public static void main (String[] arguments)
	{
		if (arguments.length != 1) {
			System.err.println ("wrong arguments !!!");
			return;
		}
		
		// Selecting the arguments.
		String broadcastPortAsString = arguments[0];
		
		// Parsing the broadcast port.
		int broadcastPort;
		try {
			broadcastPort = Integer.parseInt (broadcastPortAsString);
		} catch (NumberFormatException exception) {
			System.err.println ("wrong broadcast port !!!");
			return;
		}
		
		// Resolving the broadcast address.
		InetAddress broadcastAddress;
		try {
			broadcastAddress = InetAddress.getByName ("255.255.255.255");
		} catch (UnknownHostException exception) {
			// An unknown / unexpected network error was encountered. (Not a normal situation.)
			return;
		}
		
		// Creating and binding the socket.
		DatagramSocket socket;
		try {
			System.err.println ("creating and binding socket...");
			socket = new DatagramSocket ();
		} catch (SocketException exception) {
			// The socket can not be created or bound. (Maybe the port is already in use.)
			exception.printStackTrace (System.err);
			return;
		}
		
		// Only for debugging purposes.
		// Obtaining and printing the local socket address (the datagram source). (Which should be an instance of InetSocketAddress.)
		InetSocketAddress localSocketAddress = (InetSocketAddress) socket.getLocalSocketAddress ();
		System.err.println ("local socket address -->");
		printInetSocketAddress (localSocketAddress);
		
		// Creating the datagram destination (that is the server socket address).
		InetSocketAddress datagramDestination = new InetSocketAddress (broadcastAddress, broadcastPort);
		
		// Only for debugging purposes.
		// Printing the datagram destination address.
		System.err.println ("datagram destination -->");
		printInetSocketAddress (datagramDestination);
		
		// Set the counter.
		int counter = 10;
		
		// Sending messages
		while (counter > 0) {
			
			// Waiting some time (1 second) before sending.
			try {
				Thread.sleep (1000);
			} catch (InterruptedException exception) {
				// An unknown / unexpected network error was encountered. (Not a normal situation.)
				return;
			}
			
			// Creating the message.
			String message = "MOTD--" + System.currentTimeMillis ();
			
			// Creating the datagram backing buffer.
			byte[] datagramBuffer = message.getBytes ();
			int datagramBufferOffset = 0;
			int datagramBufferSize = datagramBuffer.length;
			
			// Creating the datagram.
			DatagramPacket datagram;
			try {
				System.err.println ("creating datagram...");
				System.err.println ("    message = " + message);
				datagram = new DatagramPacket (datagramBuffer, datagramBufferOffset, datagramBufferSize, datagramDestination);
			} catch (SocketException exception) {
				// An unknown / unexpected network error was encountered. (Not a normal situation.)
				exception.printStackTrace (System.err);
				return;
			}
			
			// Sending the datagram.
			try {
				System.err.println ("sending datagram...");
				socket.send (datagram);
			} catch (IOException exception) {
				// The datagram could not be sent. (Maybe destination is unreachable.)
				exception.printStackTrace (System.err);
				return;
			}
			
			counter--;
		}
		
		// Closing the socket.
		System.err.println ("closing socket...");
		socket.close ();
	}
	
	public static void printInetSocketAddress (InetSocketAddress socketAddress)
	{
		// Obtaining the local IP address.
		InetAddress address = socketAddress.getAddress ();
		
		// Obtaining the local port.
		int port = socketAddress.getPort ();
		
		// Printing obtained information;
		printInetAddress (address);
		System.err.println ("    port = " + port);
	}
	
	public static void printInetAddress (InetAddress address)
	{
		// Obtaining the IP as a string.
		String ipAsString = address.getHostAddress ();
		
		// Obtaining the IP as an array of bytes.
		byte[] ipAsBytes = address.getAddress ();
		
		// Obtaining the reverse host name.
		String reverseName = address.getCanonicalHostName ();
		
		// Printing the default string representation.
		System.err.println ("    address = " + address);
		
		// Printing the IP as string.
		System.err.println ("    ip as string = " + ipAsString);
		
		// Printing the IP as bytes.
		System.err.println ("    ip as bytes length = " + ipAsBytes.length);
		System.err.print ("    ip as bytes =");
		for (byte b : ipAsBytes)
			System.err.print (" " + (b));
		System.err.println ();
		
		// Printing the reverse host name.
		System.err.println ("    reverse name = " + reverseName);
	}
}