Skip to content
Snippets Groups Projects
UDPResultReceiver.java 2.33 KiB

package MV3500Cohort2020JulySeptember.homework4.Weissenberger;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * This class will be connected by an UDP sender over VPN (argon) 
 * @date 09/02/2020
 * @author Loki
 * @group Weissenberger/Goericke
 */
public class UDPResultReceiver {

    public static final int    RECEIVING_PORT = 1415;

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws IOException 
    {
        DatagramSocket udpSocket = null;
        
        try
        {
            System.out.println(UDPResultReceiver.class.getName() + " started...");
            
            // Create a UDP socket
            udpSocket = new DatagramSocket(RECEIVING_PORT);
            udpSocket.setReceiveBufferSize(1500); // how many bytes are in buffer?  MTU=1500 is good
            udpSocket.setBroadcast(false);        // we're just receiving here
            
            byte[] byteArray = new byte[1500];
            DatagramPacket receivePacket = new DatagramPacket(byteArray, byteArray.length);
            
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            DataInputStream dis = new DataInputStream(bais);
            
            String received;
            
            // You need a new receiving packet to read from every packet received
            while (true)
            {
                udpSocket.receive(receivePacket); // blocks until packet is received
                
                received  = dis.readUTF();
                
                dis.reset(); // now clear the input stream after reading, in preparation for next loop
                
                System.out.println("Received from Bernd: "+received);
                
            }
        }
        catch(IOException e)
        {
            System.err.println("Problem with UdpReceiver, see exception trace:");
            System.err.println(e);
        } 
        finally // clean up prior to exit, don't want to leave behind zombie socket
        {
            if (udpSocket != null)
                udpSocket.close();
            System.out.println(UDPResultReceiver.class.getName() + " complete."); // all done
        }
    }
}