Skip to content
Snippets Groups Projects
Commit 7e415cf0 authored by Brutzman, Don's avatar Brutzman, Don
Browse files

http and multicast examples, refactored

parent 8b70eeb8
No related branches found
No related tags found
No related merge requests found
package UdpMulticastHttpExamples;
import java.io.*;
import java.net.*;
/**
* A very simple http web-page reading example that won't work in some circumstances.
* But it will in some others.
*
* @author mcgredo
*/
public class HttpWebPageSource {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
try
{
System.out.println("HttpWebPageSource: create http connection and retrieve default page");
System.out.println("Reference: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol");
System.out.println("Reference: https://tools.ietf.org/html/rfc7230");
System.out.println();
// We request an IP to connect to a web server running on port 80.
Socket socket = new Socket("www.MovesInstitute.org", 80);
// we send a command to the web server, asking for what
// we want. Note that the format for the command is very
// specific and documented.
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
String message = "GET /index.html HTTP/1.0";
ps.print(message);
System.out.println(message);
System.out.println();
// Commands have to terminate with "carriage return/line feed"
// twice to end the request. Those are the special characters
// to have the control characters printed. Part of the http protocol!
ps.print("\r\n\r\n");
ps.flush();
// Up until now we have been reading one line only.
// But a web server will write an unknown number of lines.
// So now we read until the transmisson ends.
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
int count = 0;
while((line = br.readLine()) != null) // read from BufferedReader br one line at a time
{
count++;
System.out.println(count + ": " + line);
}
System.out.println("HttpWebPageSource: response finished");
}
catch(IOException e)
{
System.out.println("HttpWebPageSource: problem with client");
System.out.println(e);
}
}
}
package UdpMulticastHttpExamples;
import java.io.*;
import java.net.*;
/**
*
* @author mcgredo
*/
public class MulticastReceiver {
public static final String MULTICAST_ADDRESS = "239.1.2.15";
public static final int DESTINATION_PORT = 1718;
/** How many routers can be crossed */
public static final int TTL = 10;
public static void main(String[] args)
{
try
{
System.out.println("MulticastReceiver started...");
// This is a java/IPv6 problem. You should also add it to the
// arguments used to start the app, eg -Djava.net.preferIPv4Stack=true
// set in the "run" section of preferences. Also, typically
// netbeans must be restarted after these settings.
// https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache
System.setProperty("java.net.preferIPv4Stack", "true");
MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT);
multicastSocket.setTimeToLive(TTL);
InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS);
// Join group useful on receiving side
multicastSocket.joinGroup(multicastAddress);
// You can join multiple groups here
System.out.println("Multicast address/port: " + multicastAddress.getHostAddress() + "/" + DESTINATION_PORT);
System.out.println("Multicast packets received log:");
int count = 0; // initialize
while(true)
{
byte[] packetArray = new byte[1500]; // note use of typical MTU value
DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length);
multicastSocket.receive(packet);
count++;
ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData());
DataInputStream dis = new DataInputStream(bais);
String firstCharacters = new String();
char nextChar = ' ';
while (nextChar != ';') // read and build string until terminator ; found
{
nextChar = dis.readChar();
firstCharacters += nextChar;
}
if (firstCharacters.equals("quit;"))
{
System.out.println("Received \"quit;\" sentinel");
break; // exit out of reading loop
}
int index = dis.readInt();
float firstFloat = dis.readFloat();
float secondFloat = dis.readFloat();
if (count < 10) System.out.print(" "); // prettier output formatting
System.out.print(count + ". \"" + firstCharacters + "\" "); // wrap string in quote marks
System.out.println("index=" + index + ", firstFloat=" + firstFloat + " secondFloat=" + secondFloat);
}
System.out.println("MulticastReceiver loop complete.");
}
catch(IOException e)
{
System.out.println("Problem with MulticastReceiver, see exception trace:");
System.out.println(e);
}
finally // clean up after exit condition
{
// socket/database/completion cleanup code can go here, if needed.
System.out.println("MulticastReceiver finally block, complete.");
}
}
}
package UdpMulticastHttpExamples;
import java.io.*;
import java.net.*;
/**
* Looks a lot like a UDP sender.
*
* @author mcgredo
*/
public class MulticastSender {
public static final String MULTICAST_ADDRESS = "239.1.2.15"; // within reserved multicast address range
public static final int DESTINATION_PORT = 1718;
/** How many routers can be crossed */
public static final int TTL = 10;
@SuppressWarnings("SleepWhileInLoop")
public static void main(String[] args)
{
try
{
System.out.println("MulticastSender started...");
// This is a java/IPv6 problem. You should also add it to the
// arguments used to start the app, eg -Djava.net.preferIPv4Stack=true
// set in the "run" section of preferences. Also, typically
// netbeans must be restarted after these settings.
// https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache
System.setProperty("java.net.preferIPv4Stack", "true");
// multicast group we are sending to--not a single host
MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT);
multicastSocket.setTimeToLive(TTL); // time to live reduces scope of transmission
InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS);
System.out.println("Multicast address/port: " + multicastAddress.getHostAddress() + "/" + DESTINATION_PORT);
// Join group useful on receiving side
multicastSocket.joinGroup(multicastAddress);
// You can join multiple groups here
int loopSize = 20;
for (int index = 0; index < loopSize; index++)
{
// Put together a message with binary content. "ByteArrayOutputStream"
// is a java.io utility that lets us put together an array of binary
// data, which we put into the UDP packet.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
// Put together an updated packet to send
if (index < loopSize - 1)
{
// Put together an updated packet to send
dos.writeChars("MulticastSender packet " + Integer.toString(index) + ";"); // string chars for readability
dos.writeInt (index); // arbitrary data, needs Java or byte-alignment to read
dos.writeFloat(17.0f); // arbitrary data, needs Java or byte-alignment to read
dos.writeFloat(23.0f); // arbitrary data, needs Java or byte-alignment to read
}
else dos.writeChars("quit;"); // note string must include ; semicolon as termination sentinel
byte[] buffer = baos.toByteArray();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT);
multicastSocket.send(packet);
System.out.println("Sent multicast packet " + index + " of " + loopSize);
// How fast does this go? Does UDP try to slow it down, or does
// this cause network problems? (hint: yes for an unlimited send
// rate, unlike TCP). How do you know on the receiving side
// that you haven't received a duplicate UDP packet, out of
// order packet, or dropped packet? Necessary considerations.
Thread.sleep(1000); // Send 100, one per second
}
System.out.println("MulticastSender complete.");
}
catch(IOException | InterruptedException e)
{
System.out.println("Problem with MulticastSender, see exception trace:");
System.out.println(e);
}
}
}
Invocation instructions:
1. run/debug MulticastReceiver.java
2. run/debug MulticastSender.java
Program responses:
===================================================
run:
MulticastSender started...
Multicast address/port: 239.1.2.15/1718
Sent multicast packet 0 of 20
Sent multicast packet 1 of 20
Sent multicast packet 2 of 20
Sent multicast packet 3 of 20
Sent multicast packet 4 of 20
Sent multicast packet 5 of 20
Sent multicast packet 6 of 20
Sent multicast packet 7 of 20
Sent multicast packet 8 of 20
Sent multicast packet 9 of 20
Sent multicast packet 10 of 20
Sent multicast packet 11 of 20
Sent multicast packet 12 of 20
Sent multicast packet 13 of 20
Sent multicast packet 14 of 20
Sent multicast packet 15 of 20
Sent multicast packet 16 of 20
Sent multicast packet 17 of 20
Sent multicast packet 18 of 20
Sent multicast packet 19 of 20
MulticastSender complete.
BUILD SUCCESSFUL (total time: 20 seconds)
===================================================
run:
MulticastReceiver started...
Multicast address/port: 239.1.2.15/1718
Multicast packets received log:
1. "MulticastSender packet 0;" index=0, firstFloat=17.0 secondFloat=23.0
2. "MulticastSender packet 1;" index=1, firstFloat=17.0 secondFloat=23.0
3. "MulticastSender packet 2;" index=2, firstFloat=17.0 secondFloat=23.0
4. "MulticastSender packet 3;" index=3, firstFloat=17.0 secondFloat=23.0
5. "MulticastSender packet 4;" index=4, firstFloat=17.0 secondFloat=23.0
6. "MulticastSender packet 5;" index=5, firstFloat=17.0 secondFloat=23.0
7. "MulticastSender packet 6;" index=6, firstFloat=17.0 secondFloat=23.0
8. "MulticastSender packet 7;" index=7, firstFloat=17.0 secondFloat=23.0
9. "MulticastSender packet 8;" index=8, firstFloat=17.0 secondFloat=23.0
10. "MulticastSender packet 9;" index=9, firstFloat=17.0 secondFloat=23.0
11. "MulticastSender packet 10;" index=10, firstFloat=17.0 secondFloat=23.0
12. "MulticastSender packet 11;" index=11, firstFloat=17.0 secondFloat=23.0
13. "MulticastSender packet 12;" index=12, firstFloat=17.0 secondFloat=23.0
14. "MulticastSender packet 13;" index=13, firstFloat=17.0 secondFloat=23.0
15. "MulticastSender packet 14;" index=14, firstFloat=17.0 secondFloat=23.0
16. "MulticastSender packet 15;" index=15, firstFloat=17.0 secondFloat=23.0
17. "MulticastSender packet 16;" index=16, firstFloat=17.0 secondFloat=23.0
18. "MulticastSender packet 17;" index=17, firstFloat=17.0 secondFloat=23.0
19. "MulticastSender packet 18;" index=18, firstFloat=17.0 secondFloat=23.0
Received "quit;" sentinel
MulticastReceiver loop complete.
MulticastReceiver finally block, complete.
BUILD SUCCESSFUL (total time: 31 seconds)
===================================================
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