Skip to content
Snippets Groups Projects
Commit f18e1cb3 authored by brutzman's avatar brutzman
Browse files

refactor improvements to handle boolean, int, float, string. now suitable for stealing and reuse!

parent 904cbe61
No related branches found
No related tags found
No related merge requests found
...@@ -2,7 +2,6 @@ package UdpMulticastHttpExamples; ...@@ -2,7 +2,6 @@ package UdpMulticastHttpExamples;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.nio.ByteBuffer;
/** /**
* An example of receiving UDP packets. Since very often both the * An example of receiving UDP packets. Since very often both the
...@@ -11,6 +10,7 @@ import java.nio.ByteBuffer; ...@@ -11,6 +10,7 @@ import java.nio.ByteBuffer;
* *
* Start this before launching UdpSender. * Start this before launching UdpSender.
* *
* @see https://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
* @author mcgredo * @author mcgredo
* @author brutzman * @author brutzman
*/ */
...@@ -27,7 +27,6 @@ public class UdpReceiver ...@@ -27,7 +27,6 @@ public class UdpReceiver
public static void main(String[] args) throws IOException public static void main(String[] args) throws IOException
{ {
DatagramSocket udpSocket = null; DatagramSocket udpSocket = null;
int packetCount = 0;
try try
{ {
...@@ -35,34 +34,54 @@ public class UdpReceiver ...@@ -35,34 +34,54 @@ public class UdpReceiver
// Create a UDP socket // Create a UDP socket
udpSocket = new DatagramSocket(RECEIVING_PORT); udpSocket = new DatagramSocket(RECEIVING_PORT);
udpSocket.setReceiveBufferSize(1500); udpSocket.setReceiveBufferSize(1500); // how many bytes are in buffer? MTU=1500 is good
udpSocket.setBroadcast(false); // we're just receiving here udpSocket.setBroadcast(false); // we're just receiving here
ByteBuffer buffer = ByteBuffer.allocate(1500); byte[] byteArray = new byte[1500];
DatagramPacket receivePacket = new DatagramPacket(buffer.array(), buffer.capacity()); DatagramPacket receivePacket = new DatagramPacket(byteArray, byteArray.length);
float first, second; 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 // You need a new receiving packet to read from every packet received
while (true) while (true)
{ {
udpSocket.receive(receivePacket); packetCount++; // good practice to increment counter at start of loop, when possible
udpSocket.receive(receivePacket); // blocks until packet is received
// What happens if you read an integer? Two double values? *** // values of interest follow. order and types of what was sent must match what you are reading!
first = buffer.getFloat(); // alternatives: readFloat(); readInt(); dis.readUTF(); firstInt = dis.readInt();
second = buffer.getFloat(); secondFloat = dis.readFloat();
thirdString = dis.readUTF();
isEvenParity = dis.readBoolean();
dis.reset(); // clear the input stream after reading
buffer.clear(); if (isEvenParity)
padding = " ";
else padding = "";
System.out.println("first value: " + first + " second value: " + second + " packet count = " + ++packetCount); System.out.println(UdpReceiver.class.getName() +
", first int value=" + firstInt +
", second float value=" + secondFloat +
", third String value=\"" + thirdString + "\"" + // note that /" is literal quote character
" parity value=" + isEvenParity + padding +
", packet counter=" + packetCount);
} }
} }
catch(IOException e) catch(IOException e)
{ {
System.err.println("Problem with UdpReceiver, see exception trace:"); System.err.println("Problem with UdpReceiver, see exception trace:");
System.err.println(e); System.err.println(e);
} finally { }
finally // clean up prior to exit, don't want to leave behind zombie
{
if (udpSocket != null) if (udpSocket != null)
udpSocket.close(); udpSocket.close();
} }
......
...@@ -11,12 +11,14 @@ import java.net.*; ...@@ -11,12 +11,14 @@ import java.net.*;
* *
* Start this before launching UdpReceiver. * Start this before launching UdpReceiver.
* *
* @see https://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
* @author mcgredo * @author mcgredo
* @author brutzman * @author brutzman
*/ */
public class UdpSender public class UdpSender
{ {
public static final String MY_NAME = System.getProperty("user.name"); // System properties: https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
public static final String MY_NAME = System.getProperty("user.name"); // guru incantation 8)
public static final int SENDING_PORT = 1414; public static final int SENDING_PORT = 1414;
public static final int RECEIVING_PORT = 1415; public static final int RECEIVING_PORT = 1415;
public static final String DESTINATION_HOST = "localhost"; // localhost 127.0.0.1 or argon 10.1.105.1 public static final String DESTINATION_HOST = "localhost"; // localhost 127.0.0.1 or argon 10.1.105.1
...@@ -26,10 +28,15 @@ public class UdpSender ...@@ -26,10 +28,15 @@ public class UdpSender
{ {
DatagramSocket udpSocket = null; DatagramSocket udpSocket = null;
DataOutputStream dos = null; DataOutputStream dos = null;
int packetID = 0; // counter variable to send in packet
float value = -1.0f; // unreachable value is good sentinel to ensure expected changes occur
String message = "Hello MV3500"; // no really
String padding = new String();
try try
{ {
System.out.println("UdpSender started..."); System.out.println(UdpSender.class.getName() + " shows how to send simple-type values via DataOutputStream");
System.out.println(UdpSender.class.getName() + " started...");
// Create a UDP socket // Create a UDP socket
udpSocket = new DatagramSocket(SENDING_PORT); udpSocket = new DatagramSocket(SENDING_PORT);
...@@ -38,42 +45,61 @@ public class UdpSender ...@@ -38,42 +45,61 @@ public class UdpSender
// is a java.io utility that lets us put together an array of binary // is a java.io utility that lets us put together an array of binary
// data, which we put into the UDP packet. // data, which we put into the UDP packet.
ByteArrayOutputStream baos = new ByteArrayOutputStream(1500); ByteArrayOutputStream baos = new ByteArrayOutputStream(1500); // how many bytes are in buffer? MTU=1500 is good
dos = new DataOutputStream(baos); dos = new DataOutputStream(baos); // wrapper for writing values, connects both streams
// alternatives: writeFloat(17.0f); writeInt(17); writeUTF("\"hello MV3500 no really\"");
dos.writeFloat(17.0f);
dos.writeFloat(24.0f);
byte[] buffer = baos.toByteArray();
// Put together a packet to send // Put together a packet to send
// these types and order of variables must match on sender and receiver
byte[] byteArray = baos.toByteArray();
// ID of the host we are sending to // ID of the host we are sending to
InetAddress destinationAddress = InetAddress.getByName(DESTINATION_HOST); InetAddress destinationAddress = InetAddress.getByName(DESTINATION_HOST);
// ID of the host we are sending from // ID of the host we are sending from
InetAddress sourceAddress = InetAddress.getByName("localhost"); // possibly identical if source not modified InetAddress sourceAddress = InetAddress.getByName("localhost"); // possibly identical if source not modified
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, destinationAddress, RECEIVING_PORT); DatagramPacket datagramPacket = new DatagramPacket(byteArray, byteArray.length, destinationAddress, RECEIVING_PORT);
// How fast does this go? Does UDP try to slow it down, or does // Hmmm, how fast does UDP stream go? Does UDP effectively slow packets down, or does
// this cause network problems? (hint: yes for an unlimited send // this cause network problems? (hint: yes for an unlimited send rate, unlike TCP).
// rate, unlike TCP). How do you know on the receiving side // How do you know on the receiving side that you haven't received a
// that you haven't received a duplicate UDP packet, out of // duplicate UDP packet, out-of-order packet, or dropped packet? your responsibility.
// order packet, or dropped packet?
for (int index = 1; index <= 100; index++) // avoid infinite send loops in code, they can be hard to kill! for (int index = 1; index <= 100; index++) // avoid infinite send loops in code, they can be hard to kill!
{ {
udpSocket.send(packet); packetID++; // increment counter, prefer using explicit value to index
Thread.sleep(1000); // Send 100, one per second value = 100 - packetID; // countdown
System.out.println(MY_NAME + ": " + sourceAddress + " sent packet " + index + " of 100"); boolean isEvenParity = ((packetID % 2) == 0); // % is modulo operator
// values of interest follow. order and types of what was sent must match what you are reading!
dos.writeInt (packetID);
dos.writeFloat (value);
dos.writeUTF (message);
dos.writeBoolean(isEvenParity);
dos.flush(); // sends DataOutputStream to ByteArrayOutputStream
byteArray = baos.toByteArray(); // OK so go get the flushed result...
datagramPacket.setData(byteArray); // and put it in the packet...
udpSocket.send(datagramPacket); // and send it away. boom gone, nonblocking.
if (isEvenParity)
padding = " ";
else padding = "";
Thread.sleep(1000); // Send packets at rate of one per second
System.out.println(UdpSender.class.getName() + ": " + MY_NAME + " " + sourceAddress +
" sent values(" + packetID + ", " + value + ", \"" + message + "\", " + isEvenParity +
")" + padding + " as packet #" + index + " of 100");
baos.reset(); // clear the output stream after sending
} }
System.out.println("UdpSender complete."); System.out.println(UdpSender.class.getName() + " complete."); // all done
} }
catch (IOException | InterruptedException e) catch (IOException | InterruptedException e)
{ {
System.err.println("Problem with UdpSender, see exception trace:"); System.err.println("Problem with UdpSender, see exception trace:");
System.err.println(e); System.err.println(e);
} finally { }
finally // clean up prior to exit, don't want to leave behind zombies
{
if (udpSocket != null) if (udpSocket != null)
udpSocket.close(); udpSocket.close();
......
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment