4.3 Multicast sockets

In this exercise, you'll be guided through using a multicast socket, in fixing a simple distributed chat program. You are provided with a chat program that currently has a number of bugs. By examining and understanding the code, using the compiler, and by inserting various print statements, you will fix the program so that it works.

The EasyIn class can be at http://www.informatics.sussex.ac.uk/users/ianw/classes/EasyIn.class.

At the end of the exercise, you will have practised your debugging skills, be able to use simple threads and multicast sockets.

/**
 * MulticastChat.java -- 
 * Created: 2001/10/31 08:20 by Ian Wakeman
 * Revised: 2001/10/31 08:20 by Ian Wakeman (pending)
 * @author Ian Wakeman
 * @version $Id$ 
 * Changelog:
 * $log$ 
 *
 */

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

public class MulticastChat extends Thread {

    protected MulticastSocket socket = null;
    protected String name;

    public static final int port = 8001;
    public static final InetAddress groupAddress =
        InetAddress.getByName("228.5.6.7");

    public MulticastChat(String name) throws IOException {
        this.name = name;
        this.socket = new MulticastSocket(port);
    }

    public void chat() throws IOException {
        for(;;) {
            String s = name + " says: " + EasyIn.getString();
            DatagramPacket p = new DatagramPacket(s.getBytes(),
                                                  s.getBytes().length,
                                                  this.groupAddress,
                                                  this.port);
            socket.send(p);
        }
    }

    public void run() {
        byte[] buf = new byte[256];
        DatagramPacket p = new DatagramPacket(buf,buf.length);
        try {
            
            for (;;) {
                System.out.println(new String(p.getData()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        socket.close();
    }
    
    public static void main(String[] args) throws IOException {
        try {
            MulticastChat chatClient = new MulticastChat(args[0]);
            chatClient.chat();
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
            System.exit(-1);
        }
    }
}
Ian Wakeman 2005-02-22