import java.io.*;
import java.net.*;
import java.util.*;


/**
 * An example of sending a serialized object over the Internet
 * using UDP
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class CourseDatabaseSender
{

    public static void main(String[] args) throws Exception
    {
        InetAddress ip;        
        if (args.length > 0) ip = InetAddress.getByName(args[0]);
        else                 ip = InetAddress.getByName("localhost");

        // Construct and populate a CourseDatabase
        Course cross = new Course("CS/MATH",227,"Discrete Mathematics");
       
        CourseDatabase db = new CourseDatabase();
        db.add("CS139",  new Course("CS",139,"Algorithm Development"));
        db.add("CS227",  cross);
        db.add("CS240",  new Course("CS",240,"Data Structures and Algorithms"));
        db.add("MATH227", cross);

        // Construct a ByteArayOutputStream
        ByteArrayOutputStream  baos = new ByteArrayOutputStream();

        // Decorate the ByteArrayOutputStream 
        ObjectOutputStream out = new ObjectOutputStream(baos);        

        // Serialize the CourseDatabase
        out.writeObject(db);
        out.close();

        // Construct the UDP packet
        byte[]         data = baos.toByteArray();
        DatagramPacket datagram = new DatagramPacket(data, data.length, 
                                                     ip, 22801);

        // Construct the UDP socket (for sending)
        DatagramSocket socket = new DatagramSocket();
        
        // Send the serialized CourseDatabase
        socket.send(datagram);
    }
}
