Recent Changes - Search:

Distributed Computing

This website demonstrates using wikis as teaching and learning tool.

The course instructor is also happy to share the teaching materials here with those who find it readable.

Java Network Programming - Part 2

A Distributed Computing Lecture by Steven Choy

Lecture Overview: Datagram networking - Connection-oriented vs connectionless networking - Classes DatagramPacket and DatagramSocket - Datagram applications - Multicast networking Concepts - Class MulticastSocket - Multicast applications


Datagram and Multicast Networking

Connection-oriented networking

  • Based on TCP, using streams
  • Establish connection before transmitting
  • Guarantee correct data in correct order
  • More transmission overhead

Connectionless networking

  • Also called datagram networking
  • Based on UDP (User Datagram Protocol), using datagrams/packets
  • No guarantee on data arrival nor order
  • But can achieve better transmission rate

Uses of datagram networking

Why use UDP rather than TCP?

  • Timely transmission of data is required, and data reliability is not essential
    • Real-time applications, e.g. streaming audio and video
    • Quality degradation is more acceptable than delays
  • Multicast applications
  • Communication using small and independent packets
    • Simple query operations, e.g. domain-name lookups, time server queries, network analysis

Programming UDP (vs TCP)

  • UDP uses DatagramSocket to send & receive data
    • There is no server socket
    • The coding difference between UDP clients and servers are not as clear as in the case of TCP
  • UDP communicates with independent packets
    • There is no stream involved
  • UDP socket is not dedicated to a single remote host
    • We use same UDP socket to send packets to different destinations & receive packets from different sources

Class DatagramPacket

  • Represent a UDP packet
  • Max size of 65507 bytes (theoretical!)
    • 65535 - 20 (for IP header) - 8 (for UDP header)
    • Some OS/implementation impose smaller limits
  • In sender side, store data to be transmitted
    • Specify IP address & port of destination
    • Be kind! Don't use max size, e.g. 65000 bytes
  • In receiver side, act as buffer to receive data
    • Retrieve IP address & port of source
    • Prepare for the worst! Use max size, i.e. 65507 bytes
  • Constructors
// receive
DatagramPacket(byte buffer[], int length)
// transmit & receive
DatagramPacket(byte buffer[], int length, InetAddress address, int port)
  • Methods
InetAddress getAddress()
int getPort()
byte[] getData()
int getLength()
void setAddress(InetAddress address)
void setPort(int port)
void setData(byte[] buffer)
void setLength(int length)

Class DatagramSocket

  • To send and receive DatagramPacket
    • A single DatagramSocket can be used for both sending & receiving
  • Listen to a UDP port to receive packets
    • Valid ports 0-65535, 1-1023 reserved
  • Constructors
// transmit
DatagramSocket() throws SocketException;
// receive & transmit
DatagramSocket(int port) throws SocketException;
DatagramSocket(int port, InetAddress local) throws SocketException;
  • Methods
void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException
InetAddress getLocalAddress()
int getLocalPort()
void close()
setSoTimeout, getSoTimeout, setSendBufferSize, getSendBufferSize, setReceiveBufferSize, getReceiveBufferSize, connect, disconnect, getInetAddress, getPort

Sending and Receiving UDP Packet

Program to receive a packet

  • 1. Create a DatagramSocket
  • 2. Create a DatagramPacket to hold UDP datagram once received
  • 3. Call receive() of DatagramSocket to wait for a UDP datagram to be received
  • 4. The received data, sender's address and port number in the DatagramPacket can be extracted by DatagramPacket's methods
  • 5. Close the socket. This stops further reception of UDP packets

   DatagramSocket socket = new DatagramSocket (port);

   byte buffer[] = new byte[65508];
   DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

   socket.receive (packet);  

   InetAddress fromAddress = packet.getAddress ();
   int fromPort = packet.getPort ();
   int length = packet.getLength ();
   byte[] data = packet.getData ();

   socket.close();

Program to send a packet

  • 1. Create a DatagramSocket. If you don't care about the local port number to be used, let's the operating system assign one for you
  • 2. Create a DatagramPacket object and specify data, recipient's address and port number
  • 3. Call send() method of DatagramSocket to place the UDP packet into the network for delivery to the recipient. Note that the local address and port number are automatically transmitted as part of the UDP header
  • 4. Close the DatagramSocket

   DatagramSocket socket = new DatagramSocket ();

   DatagramPacket packet = new DatagramPacket
     (data, data.length, InetAddress.getByName("www.ouhk.edu.hk"), 1782);

   socket.send (packet);

   socket.close();

A UDP echo server

import java.net.*;
import java.io.*;

public class UDPEchoServer {
   protected int port;
   public UDPEchoServer (int port) {
      this.port = port;
   }

   public static void main (String[] args) throws IOException {
      if (args.length != 1) throw
        new IllegalArgumentException("Syntax: UDPEchoServer <port>");
      UDPEchoServer server = new UDPEchoServer (Integer.parseInt (args[0]));
      server.execute ();
   }

   public void execute () throws IOException {

      DatagramSocket socket = new DatagramSocket (port);
      while (true) {
         System.out.println("Waiting to receive packets");
         byte buffer[] = new byte[65508];
         DatagramPacket packet = new DatagramPacket (buffer, buffer.length);
         socket.receive (packet);
         System.out.print("* A packet is received and is echoed back to: ");
         System.out.println(packet.getAddress()+":"+packet.getPort());
         DatagramPacket response = new DatagramPacket( packet.getData(),
         packet.getLength(), packet.getAddress(), packet.getPort() );
         socket.send (response);
      }
   }
}

A UDP echo client

import java.net.*;
import java.io.*;

public class UDPEchoClient {
   protected DatagramSocket socket;
   protected DatagramPacket packet;

   public void execute (String host, int port, String message) throws IOException {
      socket = new DatagramSocket ();
      buildPacket (message, host, port);
      socket.send (packet);
      receivePacket ();
      socket.close ();
   }

   protected void buildPacket (String message, String host, int port)
    throws IOException {

      ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream ();
      DataOutputStream dataOut = new DataOutputStream (byteArrayOut);
      dataOut.writeUTF (message);
      byte[] data = byteArrayOut.toByteArray ();
      packet = new DatagramPacket
         (data, data.length,InetAddress.getByName (host), port);
   }

   protected void receivePacket () throws IOException {
      byte buffer[] = new byte[65508];
      DatagramPacket packet = new DatagramPacket (buffer, buffer.length);
      socket.receive (packet);
      ByteArrayInputStream byteArrayIn =
         new ByteArrayInputStream(packet.getData(), 0, packet.getLength());
      DataInputStream dataIn = new DataInputStream (byteArrayIn);
      String result = dataIn.readUTF ();
      System.out.println ("Received: " + result + ".");
   }

   public static void main (String[] args) throws IOException {
      if (args.length != 3) throw new IllegalArgumentException
         ("Syntax: UDPEchoClient <host> <port> <message>");
      UDPEchoClient client = new UDPEchoClient();
      client.execute(args[0], Integer.parseInt (args[1]), args[2]);
   }
}

A daytime server & client

  • Daytime Protocol - RFC 867
  • Server
    • Listen on UDP port 13
      public static final int DEFAULT_PORT = 13;
    • Reply current date and time in ASCII
      new java.util.Date().toString().getBytes("latin1");
  • Client
    • Send a packet with no content to server
      new DatagramPacket(new byte[256], 1, host, port);
    • Receive response from server

DNS over UDP

  • DNS can use UDP on UDP port 53
  • Or TCP on server TCP port 53 (TCP port ≠ UDP port)

Multicast networking

  • Put a single packet on network & it is transmitted to all interested destinations
  • Need proper network protocol & infrastructures
  • Reduce transmission traffic and server load
    • Vs. sending 1 packet to every interested destination
  • Like UDP, but send packets to multicast groups
    • Class D IP address denotes multicast group
    • 224.0.0.0 - 239.255.255.255
    • Interested destination needs to join multicast groups to receive packets (sender needs not join)

Multicast group address

An analogue
  • Class A/B/C IP address as your email address
  • Class D IP address as a Yahoo Group mailing address
    • One needs to subscribe to the Yahoo Group to receive messages
    • When a sender sends a message to the Yahoo Group, Yahoo handles and sends to all subscribers

Multicast networking

  • IGMP - Internet Group Management Protocol
    • IP standard for multicasting support
  • TTL - Time To Live
    • Max number of routers a multicast packet can cross
  • Broadcast: send packet to all IP hosts in a subnet
    • Send to a special address, usually last address in subnet address range
  • Multicast: packets can cross multiple networks

MBone

  • MBone = Internet Multicast Backbone
  • Largest deployment of multicast on the Internet
  • Multicast island: network or group of adjacent networks that supports multicast
  • TCP/IP tunnelling: scheme of moving multicast packets by putting them in regular unicast IP packets
  • TTL <= 64 restricts a packet to the local multicast island

Importance & limitations

  • Importance
    • Reduce transmission traffic
    • Reduce load on network servers
  • Limitations
    • Routers & switches need to be multicast-enabled
    • Need management tools for multicast deployment
    • Complete deployment of IP multicast over Internet is very difficult
    • No security measures to protect multicast traffic now, e.g. cannot restrict group joining

Class MulticastSocket

  • Extend DatagramSocket & add multicast capabilities
  • Provide all methods of DatagramSocket
  • Multicast, broadcast, unicast all share the same set of UDP ports
    • Java has no way to query the destination address of a received packet
  • Constructors
   // transmit
   MulticastSocket() 

   // receive & transmit
   MulticastSocket(int port) 
  • Methods
   void joinGroup(InetAddress group) throws IOException
   void leaveGroup(InetAddress group) throws IOException
   void send(DatagramPacket packet, byte ttl) throws IOException
   void setTimeToLive(int ttl) throws IOException
   int getTimeToLive() throws IOException 
   setTTL, getTTL, setInterface, getInterface

Programming multicast

  • Similar to using DatagramSocket except
    • Sending multicast packet can specify a TTL value
    • Receiving multicast packet must join a multicast group first
  • Multiple MulticastSocket can listen to the same port in a machine (DatagramSocket cannot)
  • Cannot create MulticastSocket on a UDP port being used by a DatagramSocket in same host
  • Methods receive() and send() with TTL are synchronized

Testing multicast programs

  • Even for a single computer to be both client and server, it must be connected to a TCP/IP network with multicast support
  • A standalone Windows computer may not work
  • Connecting through ISP (dial-up or broadband) may or may not work
  • Try in a LAN

A daytime broadcast server

import java.net.*;
import java.io.*;
import java.util.*;

public class DaytimeBroadcastServer {

   public static final int defaultPort = 1234;

   public static void main (String args[]) throws Exception {
      if (args.length > 1 ) throw new IllegalArgumentException
         ("Syntax: DaytimeBroadcastServer [<multicastgroup>]");
      InetAddress multicastGroup = InetAddress.getByName(
         args.length==0 ? "234.5.6.7": args[0]);
      MulticastSocket socket = new MulticastSocket();
      // socket.joinGroup(multicastGroup);
      while (true) {
         Thread.sleep(5000);
         System.out.println("Broadcast Data ...");
         String str = (new Date()).toString();
         byte[] data = str.getBytes();
         DatagramPacket packet = new DatagramPacket(
            data, data.length, multicastGroup, defaultPort);
         socket.send(packet);
      }
   }
}

A daytime broadcast client

import java.net.*;
import java.io.*;
import java.util.*;

public class DaytimeBroadcastClient {

   public static void main (String args[]) throws Exception {
      if (args.length > 1 ) throw new IllegalArgumentException
         ("Syntax: DaytimeBroadcastServer [<multicastgroup>]");
      InetAddress multicastGroup = InetAddress.getByName(
         args.length==0 ? "234.5.6.7": args[0]);
      MulticastSocket socket = new MulticastSocket(
         DaytimeBroadcastServer.defaultPort);
      socket.joinGroup(multicastGroup);
      byte[] buffer = new byte[80];
      DatagramPacket packet = new DatagramPacket (buffer, buffer.length);
      socket.receive(packet);
      String str = new String(packet.getData());
      System.out.println("Time received from " + packet.getAddress() + " is: " + str);
   }
}

Things to be done with multicast

  • Radio broadcasting on Internet
  • Watching live lectures via Internet
  • Real-time collaborating with shared virtual whiteboard
  • Read-time video-conferencing
  • Huge computer game with hundreds of users
  • Automatic software upgrade & bug-fix

Extra materials for studying Java UDP programming

From the Java Tutorials > Custom Networking > All About Datagrams.
From School of Computing, Napier University, Edinburgh
Let's start with a very simple example using UDP to transfer a single line of text. We will eventually extend this to become a very primitve text-based "chat" program.

Thanks for Reading

If you would rather like to have this lecture note in printed format, please click the print action link in the top right corner.

You are welcome to make contribution to this lecture note. You can suggest links to useful resources or draw illustration to aid understanding of some topics.

If you find any problem in this lecture note, please feel free to tell Steven via the following email address.

Edit - History - Print - Recent Changes - Search
Page last modified on October 04, 2007, at 04:39 AM