Something went wrong on our end
-
Brutzman, Don authoredBrutzman, Don authored
UDPResultReceiver.java 2.52 KiB
package MV3500Cohort2020JulySeptember.homework3.WeissenbergerGoericke;
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)
* @version 08/17/2020
* @author Loki
* @author Goericke
* @author Weissenberger
*/
public class UDPResultReceiver
{
/** port of interest
* @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */
public static final int RECEIVING_PORT = 1415;
/**
* Program invocation, execution starts here
* @param args command-line arguments
*/
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);
float result;
// You need a new receiving packet to read from every packet received
while (true)
{
udpSocket.receive(receivePacket); // blocks until packet is received
result = dis.readFloat();
dis.reset(); // now clear the input stream after reading, in preparation for next loop
System.out.println("Calculated result: "+result);
}
}
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
}
}
}