Something went wrong on our end
UdpReceiver.java 3.90 KiB
package UdpMulticastExamples;
import java.io.*;
import java.net.*;
/**
* An example of receiving UDP packets. Since very often both the
* sender and receiver are on the same host we use different ports
* for each. This prevents collision complaints from the localhost.
*
* Start this before launching UdpSender.
*
* @see https://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
* @see https://en.wikipedia.org/wiki/User_Datagram_Protocol
* @author mcgredo
* @author brutzman
*/
public class UdpReceiver
{
// public static final int SENDING_PORT = 1414; // port used by UdpSender, unneeded here
public static final int RECEIVING_PORT = 1415;
public static final String DESINATION_HOST = "localhost";
/**
* @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(UdpReceiver.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);
boolean isEvenParity;
int packetCount = 0;
int firstInt;
float secondFloat;
String thirdString;
String padding;
// You need a new receiving packet to read from every packet received
while (true)
{
packetCount++; // good practice to increment counter at start of loop, when possible
udpSocket.receive(receivePacket); // blocks until packet is received
// values of interest follow. order and types of what was sent must match what you are reading!
firstInt = dis.readInt(); // packetID
secondFloat = dis.readFloat();
thirdString = dis.readUTF(); // string value with guaranteed encoding, matches UTF-8 is 8 bit
isEvenParity = dis.readBoolean(); // ok, we've gotten everything we're looking for.
dis.reset(); // now clear the input stream after reading, in preparation for next loop
if (isEvenParity)
padding = " ";
else padding = "";
System.out.println("[" + UdpReceiver.class.getName() + "]" +
" packetID=" + firstInt + // have output message use same name as sender
", second float value=" + secondFloat +
", third String value=\"" + thirdString + "\"" + // note that /" is literal quote character
" isPacketIdEvenParity=" + isEvenParity + "," + padding +
" packet counter=" + packetCount);
}
}
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(UdpReceiver.class.getName() + " complete."); // all done
}
}
}