import java.io.*;
import java.net.*;

/**
 * A socket that is used to receive an expiring sequence of datagrams.
 * That is, a socket that is used to receive a sequence of
 * datagrams, each of which expires when the next becomes available.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ESDReceivingSocket
{
    private DatagramSocket         ds;
    private int                    PAYLOAD_LENGTH;


    /**
     * Explicit Value Constructor
     *
     * @param port   The port to use
     */
    public ESDReceivingSocket(int port) throws SocketException
    {
	ds = new DatagramSocket(port);
	PAYLOAD_LENGTH = ESDSendingSocket.PAYLOAD_LENGTH;
    }

    /**
     * Close this socket
     */
    public void close()
    {
       ds.close();
    }

    /**
     * Receive a packet
     *
     * @param p   The DatagramPacket to fill
     */
    public void receive(DatagramPacket p) throws IOException
    {
	byte[]              data, esdData;
	DatagramPacket      packet;


	esdData = new byte[PAYLOAD_LENGTH+1];
	packet = new DatagramPacket(esdData, esdData.length);
	ds.receive(packet);
	esdData = packet.getData();

	// Copy the appropriate bytes into the new array
	data = new byte[PAYLOAD_LENGTH];
	System.arraycopy(esdData, p.getOffset(), 
			 data, 0, PAYLOAD_LENGTH);

	// Fill the datagram packet to be returned
	p.setAddress(packet.getAddress());
	p.setData(data, packet.getOffset(), PAYLOAD_LENGTH);
	p.setPort(packet.getPort());

	// An acknowledgement is required so negate 
	// the packet number and send it back
	esdData[esdData.length-1]=(byte)
	                          ((-1)*(int)(esdData[PAYLOAD_LENGTH]));

	ds.send(packet);
    }
}
