diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduReceiverA.java b/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduReceiverA.java new file mode 100644 index 0000000000000000000000000000000000000000..79f2250868f2450910c007b08e1aef4ab14f3a41 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduReceiverA.java @@ -0,0 +1,95 @@ +package MV3500Cohort2018JulySeptember.FinalProject.CainThomersonFinal; + +import java.net.*; +import java.util.*; +import edu.nps.moves.disutil.*; +import edu.nps.moves.dis.*; +import java.io.IOException; + +/** + * Receives PDUs from the network in IEEE DIS format. + * Adapted from OpenDIS library example package edu.nps.moves.examples + * + * @author DMcG + */ +public class C_T_EspduReceiverA +{ + /** Max size of a PDU in binary format that we can receive. This is actually + * somewhat outdated--PDUs can be larger--but this is a reasonable starting point. + */ + public static final int MAX_PDU_SIZE = 8192; + + /** Default multicast group address we send on. */ + public static final String DEFAULT_MULTICAST_ADDRESS = "239.1.2.3"; + + /** Default multicast port used, matches Wireshark DIS capture default */ + public static final int DEFAULT_MULTICAST_PORT = 3000; + + public static void main(String args[]) + { + System.out.println("DisExamples.EspduReceiver started..."); + + MulticastSocket socket; + DatagramPacket packet; + InetAddress address; + PduFactory pduFactory = new PduFactory(); + + try { + // Specify the socket to receive data + socket = new MulticastSocket(DEFAULT_MULTICAST_PORT); + socket.setBroadcast(true); + + while (true) // Loop infinitely, receiving datagrams + { + byte buffer[] = new byte[MAX_PDU_SIZE]; + packet = new DatagramPacket(buffer, buffer.length); + + socket.receive(packet); + + List<Pdu> pduBundle = pduFactory.getPdusFromBundle(packet.getData()); + System.out.println("Bundle size is " + pduBundle.size()); + + Iterator iterator = pduBundle.iterator(); + + while(iterator.hasNext()) + { + Pdu aPdu = (Pdu)iterator.next(); + + System.out.print("Recieved PDU of type: " + aPdu.getClass().getName()); + if(aPdu instanceof EntityStatePdu) + { + EntityID eid = ((EntityStatePdu)aPdu).getEntityID(); + Vector3Double position = ((EntityStatePdu)aPdu).getEntityLocation(); + System.out.print("\nEID: [" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] "); + System.out.print("\nResupply source location: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]\n\n"); + //System.out.print(" FARP WTF recieving location: [" + newPos.getX() + ", " + newPos.getY() + ", " + newPos.getZ() + "]"); + } + + if(aPdu instanceof ServiceRequestPdu) + { + EntityID eid = ((ServiceRequestPdu)aPdu).getRequestingEntityID(); + short serviceType = ((ServiceRequestPdu)aPdu).getServiceTypeRequested(); + String serviceReqestTypeString = "null"; + if (serviceType == 0) + serviceReqestTypeString = "Other"; + if (serviceType == 1) + serviceReqestTypeString = "Resupply"; + if (serviceType == 2) + serviceReqestTypeString = "Repair"; + + List<SupplyQuantity> supplies = ((ServiceRequestPdu)aPdu).getSupplies(); + + System.out.println(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] "); + System.out.println(" Service Type Requested: [" + serviceType + ", " + serviceReqestTypeString + "]"); + System.out.println(" Supply Quantity: [" + supplies.toString() + "]\n\n"); + } + } // end trop through PDU bundle + } // end while + } // End try + catch (IOException e) + { + System.out.println("Problem with DisExamples.EspduReceiver, see exception trace:"); + System.out.println(e); + } + } // end main +} // end class diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduSenderA.java b/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduSenderA.java index 81c43958d75293ab3b7d4eae0eddbf984a78d246..95b29a5e1cf1bf7a2d10ac0f89d483d63c974c76 100644 --- a/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduSenderA.java +++ b/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduSenderA.java @@ -1,156 +1,278 @@ +package MV3500Cohort2018JulySeptember.FinalProject.CainThomersonFinal; -package MV3500Cohort2018JulySeptember.FinalProject.CainThomersonFinal; +import java.io.*; +import java.net.*; +import java.util.*; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.MulticastSocket; -import java.util.Properties; import edu.nps.moves.dis.*; import edu.nps.moves.disutil.CoordinateConversions; import edu.nps.moves.disutil.DisTime; /** + * Creates and sends ESPDUs in IEEE binary format. Adapted from OpenDIS library + * example package edu.nps.moves.examples * - * @author danielcain + * @author DMcG */ public class C_T_EspduSenderA { - public static final int NUMBER_TO_SEND = 4000; - - public enum NetworkMode{ - UNICAST, MULTICAST, BROADCAST - }; - - /** default multicast group we send on */ - public static final String DEFAULT_MULTICAST_GROUP="239.1.2.4"; - - /** Port we send on */ - public static final int DIS_DESTINATION_PORT = 3000; - - -public static void main(String args[]) -{ - /** an entity state pdu */ - EntityStatePdu espdu = new EntityStatePdu(); - MulticastSocket socket = null; - DisTime disTime = DisTime.getInstance(); - int alternator = -1; - // ICBM coordinates for my office - double lat = 32.595517; - double lon = -117.877000; - int port = DIS_DESTINATION_PORT; - NetworkMode mode = NetworkMode.MULTICAST; - InetAddress destinationIp = null; - - try - { - destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); - } - catch(Exception e) - { - System.out.println(e + " Cannot create multicast address"); - System.exit(0); - } - - // All system properties, passed in on the command line via -Dattribute=value - Properties systemProperties = System.getProperties(); - // IP address we send to - String destinationIpString = systemProperties.getProperty("destinationIp"); - // Port we send to, and local port we open the socket on - String portString = systemProperties.getProperty("port"); - // Network mode: unicast, multicast, broadcast - String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast - - // Set up a socket to send information - try - { - // Port we send to - if(portString != null) - port = Integer.parseInt(portString); - - socket = new MulticastSocket(DIS_DESTINATION_PORT); - - // Where we send packets to, the destination IP address - if(destinationIpString != null) - { - destinationIp = InetAddress.getByName(destinationIpString); - } - - // Type of transport: unicast, broadcast, or multicast - if(networkModeString != null) - { - if(networkModeString.equalsIgnoreCase("unicast")) - mode = NetworkMode.UNICAST; - else if(networkModeString.equalsIgnoreCase("broadcast")) - mode = NetworkMode.BROADCAST; - else if(networkModeString.equalsIgnoreCase("multicast")) - { - mode = NetworkMode.MULTICAST; - if(!destinationIp.isMulticastAddress()) - { - throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); - } - socket.joinGroup(destinationIp); - } - } // end networkModeString - } - catch(Exception e) - { - System.out.println("Unable to initialize networking. Exiting."); - System.out.println(e); - System.exit(-1); - } - espdu.setExerciseID((short)1); - EntityID eid = espdu.getEntityID(); - eid.setSite(100); // 0 is apparently not a valid site number, per the spec - eid.setApplication(1); - eid.setEntity(2); - EntityType entityType = espdu.getEntityType(); - entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) - entityType.setCountry(225); // USA - entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) - entityType.setCategory((short)1); // Tank - entityType.setSubcategory((short)1); // M1 Abrams - entityType.setSpec((short)3); // M1A2 Abrams - try - { - System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); - for(int idx = 0; idx < NUMBER_TO_SEND; idx++) - { - eid.setEntity(idx+1); - int ts = disTime.getDisAbsoluteTimestamp(); - espdu.setTimestamp(ts); - double direction = Math.pow((double)(-1.0), (double)(idx)); - lon = lon + (direction * 0.00006); - double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); - Vector3Double location = espdu.getEntityLocation(); - location.setX(disCoordinates[0]); - location.setY(disCoordinates[1]); - location.setZ(disCoordinates[2]); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - espdu.marshal(dos); - byte[] data = baos.toByteArray(); - DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(DEFAULT_MULTICAST_GROUP), DIS_DESTINATION_PORT); - socket.send(packet); - Thread.sleep(3000); - location = espdu.getEntityLocation(); - System.out.println("Espdu #" + idx + " EID=[" + eid.getSite() + "," + eid.getApplication() + "," + eid.getEntity() + "]"); - //System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); - double c[] = {location.getX(), location.getY(), location.getZ()}; - double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); - System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); - } - } - catch(Exception e) - { - System.out.println(e); - } - -} + public static final int NUMBER_TO_SEND = 5000; - -} + public enum NetworkMode { + UNICAST, MULTICAST, BROADCAST + }; + + /** + * Default multicast group address we send on. + */ + public static final String DEFAULT_MULTICAST_ADDRESS = "239.1.2.3"; + + /** + * Default multicast port used, matches Wireshark DIS capture default + */ + public static final int DEFAULT_MULTICAST_PORT = 3000; + + /** + * Possible system properties, passed in via -Dattr=val networkMode: + * unicast, broadcast, multicast destinationIp: where to send the packet. If + * in multicast mode, this can be multicast. To determine broadcast + * destination IP, use an online broadcast address calculator, for example + * http://www.remotemonitoringsystems.ca/broadcast.php If in multicast mode, + * a join() will be done on the multicast address. port: port used for both + * source and destination. + * + * @param args + */ + public static void main(String args[]) + { + System.out.println("DisExamples.EspduSender started... send " + NUMBER_TO_SEND + " ESPDUs, initial index=0"); + + //Establish the Requesting Unit EnityState PDU + EntityStatePdu requestingUnitEsPdu = new EntityStatePdu(); + + //Initialize the MulticastSocket to null + MulticastSocket socket = null; + + //Initialize the DIS time (this will be used later in the code + DisTime disTime = DisTime.getInstance(); // TODO explain + //int alternator = -1; + + // Lat and Long Coordinates that will be used for the location of the Requesting Unit + double lat = 36.59; + double lon = -121.87; + + // Initialize the Port, Mode, and Destination IP + int port = DEFAULT_MULTICAST_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; + + //Use a try/catch to ensure the you can connect to the Destination IP + try { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_ADDRESS); + } catch (UnknownHostException e) { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try { + // Port we send to + if (portString != null) + { + port = Integer.parseInt(portString); + } + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if (destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + if (networkModeString != null) { + if (networkModeString.equalsIgnoreCase("unicast")) + { + mode = NetworkMode.UNICAST; + } + else if (networkModeString.equalsIgnoreCase("broadcast")) { + mode = NetworkMode.BROADCAST; + } + else if (networkModeString.equalsIgnoreCase("multicast")) { + mode = NetworkMode.MULTICAST; + if (!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + socket.joinGroup(destinationIp); + } + } + } + catch (IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. + //The exercise ID is a way to differentiate between different virtual worlds on one network. + requestingUnitEsPdu.setExerciseID((short) 1); + + // The EID is the unique identifier for objects in the world. + EntityID entityID = requestingUnitEsPdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + // Set the entity type. (Check SISO for a list of enumerations) + EntityType entityType = requestingUnitEsPdu.getEntityType(); + entityType.setEntityKind((short) 1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short) 1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short) 1); // Tank + entityType.setSubcategory((short) 1); // M1 Abrams + entityType.setSpec((short) 3); // M1A2 Abrams + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + + for (int index = 0; index < NUMBER_TO_SEND; index++) { + //DIS Time must be used for this because DIS requires it. + int timestamp = disTime.getDisAbsoluteTimestamp(); + requestingUnitEsPdu.setTimestamp(timestamp); + + //Set up longitude to be changing throughout the running of the program + double direction = Math.pow((double) (-1.0), (double) (index)); + lon = lon + (direction * 0.00006); + + //Convert the lat and long coordinates to cartisian coordinates required by DIS + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = requestingUnitEsPdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + requestingUnitEsPdu.marshal(dos); + + //SERVICE_REQUEST + ServiceRequestPdu serviceRequest = new ServiceRequestPdu(); + serviceRequest.setRequestingEntityID(entityID); + serviceRequest.setServiceTypeRequested((short) 1); //Resupply + List<SupplyQuantity> pSupplies = new ArrayList<SupplyQuantity>(); + pSupplies.add(new SupplyQuantity()); + serviceRequest.setSupplies(pSupplies); + + //RESUPPLY_OFFER + ResupplyOfferPdu resupplyOffer = new ResupplyOfferPdu(); + + byte[] serviceRequestArray = serviceRequest.marshal(); + //FirePdu fire = new FirePdu(); + //byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator iterator = broadcastAddresses.iterator(); + while (iterator.hasNext()) + { + InetAddress broadcast = (InetAddress) iterator.next(); + System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, port); + socket.send(packet); + // TODO experiment with these! 8) + //packet = new DatagramPacket(fireArray, fireArray.length, broadcast, port); // alternate + packet = new DatagramPacket(serviceRequestArray, serviceRequestArray.length, broadcast, port); // alternate + socket.send(packet); + } + + // Send every 1 sec. Otherwise all this will be all over in a fraction of a second. + Thread.sleep(1000); // msec + + location = requestingUnitEsPdu.getEntityLocation(); + + System.out.println("Espdu #" + index + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + } + } + catch (IOException | InterruptedException e) + { + System.out.println("Problem with DisExamples.EspduSender, see exception trace:"); + System.out.println(e); + } + } + + /** + * A number of sites get all snippy about using 255.255.255.255 for a + * broadcast address; it trips their security software and they kick you off + * their network. (Comcast, NPS.) This determines the broadcast address for + * all connected interfaces, based on the IP and subnet mask. If you have a + * dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--e.g. running VMWare on your laptop with a local IP this will also + * pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while (interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface) interfaces.nextElement(); + + if (anInterface.isUp()) + { + Iterator iterator = anInterface.getInterfaceAddresses().iterator(); + while (iterator.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress) iterator.next(); + if ((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + { + continue; + } + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if (broadcastAddress != null) + { + broadcastAddresses.add(broadcastAddress); + } + } + } + } + } + catch (SocketException e) + { + System.out.println("Problem with DisExamples.EspduSender.getBroadcastAddresses(), see exception trace:"); + System.out.println(e); + } + return broadcastAddresses; + } +} diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduSenderB.java b/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduSenderB.java deleted file mode 100644 index bfb32ec241ac5d3ffc7fa82dcab61a4684ae9799..0000000000000000000000000000000000000000 --- a/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduSenderB.java +++ /dev/null @@ -1,204 +0,0 @@ - -package MV3500Cohort2018JulySeptember.FinalProject.CainThomersonFinal; - -import java.io.*; -import java.net.*; -import java.util.*; -import edu.nps.moves.dis.*; -import edu.nps.moves.disutil.CoordinateConversions; -import edu.nps.moves.disutil.DisTime; - - -/** - * - * @author danielcain - */ -public class C_T_EspduSenderB { -public static final int NUMBER_TO_SEND = 4000; - public enum NetworkMode{ - UNICAST, MULTICAST, BROADCAST - }; - /** default multicast group we send on */ - public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; - /** Port we send on */ - public static final int DIS_DESTINATION_PORT = 2800; - -public static void main(String args[]) -{ - /** an entity state pdu */ - EntityStatePdu espdu = new EntityStatePdu(); - MulticastSocket socket = null; - DisTime disTime = DisTime.getInstance(); - int alternator = -1; - - // ICBM coordinates for my office - double lat = 32.595517; - double lon = -117.877000; - - int port = DIS_DESTINATION_PORT; - NetworkMode mode = NetworkMode.MULTICAST; - InetAddress destinationIp = null; - try - { - destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); - } - catch(Exception e) - { - System.out.println(e + " Cannot create multicast address"); - System.exit(0); - } - - // All system properties, passed in on the command line via -Dattribute=value - Properties systemProperties = System.getProperties(); - - // IP address we send to - String destinationIpString = systemProperties.getProperty("destinationIp"); - - // Port we send to, and local port we open the socket on - String portString = systemProperties.getProperty("port"); - - // Network mode: unicast, multicast, broadcast - String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast - - - // Set up a socket to send information - try - { - // Port we send to - if(portString != null) - port = Integer.parseInt(portString); - - socket = new MulticastSocket(DIS_DESTINATION_PORT); - - // Where we send packets to, the destination IP address - if(destinationIpString != null) - { - destinationIp = InetAddress.getByName(destinationIpString); - } - - // Type of transport: unicast, broadcast, or multicast - if(networkModeString != null) - { - if(networkModeString.equalsIgnoreCase("unicast")) - mode = NetworkMode.UNICAST; - else if(networkModeString.equalsIgnoreCase("broadcast")) - mode = NetworkMode.BROADCAST; - else if(networkModeString.equalsIgnoreCase("multicast")) - { - mode = NetworkMode.MULTICAST; - if(!destinationIp.isMulticastAddress()) - { - throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); - } - - socket.joinGroup(destinationIp); - - } - } // end networkModeString - } - catch(Exception e) - { - System.out.println("Unable to initialize networking. Exiting."); - System.out.println(e); - System.exit(-1); - } - - - espdu.setExerciseID((short)1); - EntityID eid = espdu.getEntityID(); - eid.setSite(200); // 0 is apparently not a valid site number, per the spec - eid.setApplication(1); - eid.setEntity(2); - EntityType entityType = espdu.getEntityType(); - entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) - entityType.setCountry(225); // USA - entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) - entityType.setCategory((short)1); // Tank - entityType.setSubcategory((short)1); // M1 Abrams - entityType.setSpec((short)3); // M1A2 Abrams - - try - { - - System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); - for(int idx = 0; idx < NUMBER_TO_SEND; idx++) - { - eid.setEntity(idx+1); - - int ts = disTime.getDisAbsoluteTimestamp(); - espdu.setTimestamp(ts); - double direction = Math.pow((double)(-1.0), (double)(idx)); - lon = lon + (direction * 0.00006); - double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); - Vector3Double location = espdu.getEntityLocation(); - location.setX(disCoordinates[0]); - location.setY(disCoordinates[1]); - location.setZ(disCoordinates[2]); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - espdu.marshal(dos); - byte[] data = baos.toByteArray(); - DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(DEFAULT_MULTICAST_GROUP), DIS_DESTINATION_PORT); - socket.send(packet); - Thread.sleep(3000); - location = espdu.getEntityLocation(); - System.out.println("Espdu #" + idx + " EID=[" + eid.getSite() + "," + eid.getApplication() + "," + eid.getEntity() + "]"); - //System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); - double c[] = {location.getX(), location.getY(), location.getZ()}; - double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); - System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); - } - } - catch(Exception e) - { - System.out.println(e); - } - -} - - /** - * @return set of all broadcast addresses - */ - public static Set<InetAddress> getBroadcastAddresses() - { - Set<InetAddress> bcastAddresses = new HashSet<InetAddress>(); - Enumeration interfaces; - - try - { - interfaces = NetworkInterface.getNetworkInterfaces(); - - while(interfaces.hasMoreElements()) - { - NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); - - if(anInterface.isUp()) - { - Iterator it = anInterface.getInterfaceAddresses().iterator(); - while(it.hasNext()) - { - InterfaceAddress anAddress = (InterfaceAddress)it.next(); - if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) - continue; - - //System.out.println("Getting bcast address for " + anAddress); - InetAddress abcast = anAddress.getBroadcast(); - if(abcast != null) - bcastAddresses.add(abcast); - } - } - } - - } - catch(Exception e) - { - e.printStackTrace(); - System.out.println(e); - } - - return bcastAddresses; - } - -} - - diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduTCP_RecA_SendB.java b/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduTCP_RecA_SendB.java deleted file mode 100644 index 41ac0fae52493b44bebe4366eec9bc3b028cdee3..0000000000000000000000000000000000000000 --- a/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduTCP_RecA_SendB.java +++ /dev/null @@ -1,140 +0,0 @@ - -package MV3500Cohort2018JulySeptember.FinalProject.CainThomersonFinal; - -import java.io.*; -import java.net.*; -import java.util.*; -import edu.nps.moves.dis.*; -import edu.nps.moves.disutil.DisTime; -import edu.nps.moves.disutil.PduFactory; - -public class C_T_EspduTCP_RecA_SendB { - -public static final int NUMBER_TO_SEND = 4000; - public enum NetworkMode{ - UNICAST, MULTICAST, BROADCAST - }; - /** default multicast group we send on */ - public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; - public static final int MAX_PDU_SIZE = 8192; - public static final int TCP_DESTINATION_PORT = 2999; - /** Port we send on */ - public static final int DIS_DESTINATION_PORT = 2800; -/** Possible system properties, passed in via -Dattr=val - * port: port used for both source and destination. - * @param args - */ -public static void main(String args[]) -{ - /** an entity state pdu */ - EntityStatePdu espdu = new EntityStatePdu(); - MulticastSocket socket = null; - DisTime disTime = DisTime.getInstance(); - int alternator = -1; - int port = DIS_DESTINATION_PORT; - NetworkMode mode = NetworkMode.MULTICAST; - InetAddress destinationIp = null; - PduFactory pduFactory = new PduFactory(); - try - { - destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); - } - catch(Exception e) - { - System.out.println(e + " Cannot create multicast address"); - System.exit(0); - } - Properties systemProperties = System.getProperties(); - String destinationIpString = systemProperties.getProperty("destinationIp"); - String portString = systemProperties.getProperty("port"); - String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast - try - { - - // Port we send to - if(portString != null) - port = Integer.parseInt(portString); - - socket = new MulticastSocket(DIS_DESTINATION_PORT); - - // Where we send packets to, the destination IP address - if(destinationIpString != null) - { - destinationIp = InetAddress.getByName(destinationIpString); - } - - // Type of transport: unicast, broadcast, or multicast - if(networkModeString != null) - { - if(networkModeString.equalsIgnoreCase("unicast")) - mode = NetworkMode.UNICAST; - else if(networkModeString.equalsIgnoreCase("broadcast")) - mode = NetworkMode.BROADCAST; - else if(networkModeString.equalsIgnoreCase("multicast")) - { - mode = NetworkMode.MULTICAST; - if(!destinationIp.isMulticastAddress()) - { - throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); - } - - socket.joinGroup(destinationIp); - - } - } // end networkModeString - } - catch(Exception e) - { - System.out.println("Unable to initialize networking. Exiting."); - System.out.println(e); - System.exit(-1); - } - - try - { - int connectionCount = 0; - DatagramSocket ds = new DatagramSocket(TCP_DESTINATION_PORT); - - while(true){ - try - { - byte buffer[] = new byte[MAX_PDU_SIZE]; - DatagramPacket tcpPacket = new DatagramPacket(buffer, buffer.length); - ds.receive(tcpPacket); - connectionCount++; - System.out.println("Current PDUs transferred over TCP: "+ connectionCount); - List<Pdu> pduBundle = pduFactory.getPdusFromBundle(tcpPacket.getData()); - //System.out.println("Bundle size is " + pduBundle.size()); - Iterator it = pduBundle.iterator(); - - while(it.hasNext()){ - //System.out.println("Entity ID transferred: "); - Pdu aPdu = (Pdu)it.next(); - //System.out.print("got PDU of type: " + aPdu.getClass().getName()); - if(aPdu instanceof EntityStatePdu){ - EntityID eid = ((EntityStatePdu)aPdu).getEntityID(); - System.out.println("Entity ID transferred: "+eid.getEntity()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - aPdu.marshal(dos); - byte[] data = baos.toByteArray(); - DatagramPacket udpPacket = new DatagramPacket(data, data.length, InetAddress.getByName(DEFAULT_MULTICAST_GROUP), DIS_DESTINATION_PORT); - socket.send(udpPacket); - } - } - } - catch(Exception e) - { - System.out.println(e); - } - } - } - catch(Exception e) - { - System.out.println(e); - } - -} - - -} diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduTCP_RecB_SendA.java b/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduTCP_RecB_SendA.java deleted file mode 100644 index 4336377c0ae7d91c61820f24af4875802375eced..0000000000000000000000000000000000000000 --- a/deliverables/src/MV3500Cohort2018JulySeptember/FinalProject/CainThomersonFinal/C_T_EspduTCP_RecB_SendA.java +++ /dev/null @@ -1,151 +0,0 @@ - -package MV3500Cohort2018JulySeptember.FinalProject.CainThomersonFinal; - -import java.io.*; -import java.net.*; -import java.util.*; -import edu.nps.moves.dis.*; -import edu.nps.moves.disutil.DisTime; -import edu.nps.moves.disutil.PduFactory; - -public class C_T_EspduTCP_RecB_SendA { - -public static final int NUMBER_TO_SEND = 4000; - - public enum NetworkMode{ - UNICAST, MULTICAST, BROADCAST - }; - public static final int MAX_PDU_SIZE = 8192; - /** default multicast group we send on */ - public static final String DEFAULT_MULTICAST_GROUP="239.1.2.4"; - public static final int TCP_DESTINATION_PORT = 2998; - /** Port we send on */ - public static final int DIS_DESTINATION_PORT = 3000; - -public static void main(String args[]) -{ - /** an entity state pdu */ - EntityStatePdu espdu = new EntityStatePdu(); - MulticastSocket socket = null; - DisTime disTime = DisTime.getInstance(); - int alternator = -1; - - int port = DIS_DESTINATION_PORT; - NetworkMode mode = NetworkMode.MULTICAST; - InetAddress destinationIp = null; - PduFactory pduFactory = new PduFactory(); - - try - { - destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); - } - catch(Exception e) - { - System.out.println(e + " Cannot create multicast address"); - System.exit(0); - } - - // All system properties, passed in on the command line via -Dattribute=value - Properties systemProperties = System.getProperties(); - - // IP address we send to - String destinationIpString = systemProperties.getProperty("destinationIp"); - - // Port we send to, and local port we open the socket on - String portString = systemProperties.getProperty("port"); - - // Network mode: unicast, multicast, broadcast - String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast - // Set up a socket to send information - try - { - - // Port we send to - if(portString != null) - port = Integer.parseInt(portString); - - socket = new MulticastSocket(DIS_DESTINATION_PORT); - - // Where we send packets to, the destination IP address - if(destinationIpString != null) - { - destinationIp = InetAddress.getByName(destinationIpString); - } - - // Type of transport: unicast, broadcast, or multicast - if(networkModeString != null) - { - if(networkModeString.equalsIgnoreCase("unicast")) - mode = NetworkMode.UNICAST; - else if(networkModeString.equalsIgnoreCase("broadcast")) - mode = NetworkMode.BROADCAST; - else if(networkModeString.equalsIgnoreCase("multicast")) - { - mode = NetworkMode.MULTICAST; - if(!destinationIp.isMulticastAddress()) - { - throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); - } - - socket.joinGroup(destinationIp); - - } - } // end networkModeString - } - catch(Exception e) - { - System.out.println("Unable to initialize networking. Exiting."); - System.out.println(e); - System.exit(-1); - } - - try - { - int connectionCount = 0; - DatagramSocket ds = new DatagramSocket(TCP_DESTINATION_PORT); - - while(true){ - try - { - byte buffer[] = new byte[MAX_PDU_SIZE]; - DatagramPacket tcpPacket = new DatagramPacket(buffer, buffer.length); - ds.receive(tcpPacket); - //Socket clientConnection = serverSocket.accept(); - connectionCount++; - System.out.println("Current PDUs transferred over TCP: "+ connectionCount); - List<Pdu> pduBundle = pduFactory.getPdusFromBundle(tcpPacket.getData()); - //System.out.println("Bundle size is " + pduBundle.size()); - Iterator it = pduBundle.iterator(); - - while(it.hasNext()){ - //System.out.println("Entity ID transferred: "); - Pdu aPdu = (Pdu)it.next(); - //System.out.print("got PDU of type: " + aPdu.getClass().getName()); - if(aPdu instanceof EntityStatePdu){ - EntityID eid = ((EntityStatePdu)aPdu).getEntityID(); - System.out.println("Entity ID transferred: "+eid.getEntity()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - aPdu.marshal(dos); - byte[] data = baos.toByteArray(); - DatagramPacket udpPacket = new DatagramPacket(data, data.length, InetAddress.getByName(DEFAULT_MULTICAST_GROUP), DIS_DESTINATION_PORT); - socket.send(udpPacket); - } - } - } - catch(Exception e) - { - System.out.println(e); - } - } - } - catch(Exception e) - { - System.out.println(e); - } - -} - - - -} diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/homework2/JacksonTcpClient.java b/deliverables/src/MV3500Cohort2018JulySeptember/homework2/JacksonTcpClient.java new file mode 100644 index 0000000000000000000000000000000000000000..81cd8c3715b685e93b130c01cc95de85ba7cd63e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JulySeptember/homework2/JacksonTcpClient.java @@ -0,0 +1,57 @@ +package MV3500Cohort2018JulySeptember.homework2; + +import java.io.*; +import java.net.*; + +/** + * Before, we always used telnet to connect to the server. Here we are now + * writing our own program to do the connection. + * + * As you will see, when we run this after we start the server we will see the + * same string telnet printed, sent by the server. The output at the server will + * show different socket pairs for each time we ran it. + * + * @author mcgredo + */ +public class JacksonTcpClient { + + public final static String LOCALHOST = "0:0:0:0:0:0:0:1"; // String constant, i.e. 127.0.0.1 + + + public static void main(String[] args) { + int i = 1; + try { + while (true) { + //System.out.println("TcpClient creating socket..."); + + // We request an IP to connect to ("localhost") and + // port number at that IP (2317). This establishes + // a connection to that IP in the form of the Socket + // object; the server uses a ServerSocket to wait for + // connections. + Socket socket = new Socket(LOCALHOST, 2317); // locohost? + + // Now hook everything up (i.e. set up the streams), Java style: + InputStream is = socket.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + // Read the single line written by the server. We'd + // do things a bit differently if many lines to be read + // from the server, instead of one only. + String serverMessage = br.readLine(); + System.out.println("=================================================="); + System.out.println("Connection #" + i); + System.out.println("The message the server sent was " + serverMessage); + i++; + // socket gets closed, either automatically/silently this code (or possibly by server) + } // end while(true) + } + catch (IOException e) { + System.out.println("Problem with client: "); // describe what is happening + System.out.println(e); + } + // program exit: tell somebody about that + System.out.println("client exit"); + } +} diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/homework2/JacksonTcpServer.java b/deliverables/src/MV3500Cohort2018JulySeptember/homework2/JacksonTcpServer.java new file mode 100644 index 0000000000000000000000000000000000000000..004ebb63de5d11da9810f0f38ad14c996e599f66 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JulySeptember/homework2/JacksonTcpServer.java @@ -0,0 +1,80 @@ +package MV3500Cohort2018JulySeptember.homework2; + +import java.io.*; +import java.net.*; + +/** + * Very slightly more complex than example1. A complete copy of example 2. The + * only thing this does differently is introduce a loop into the response, so + * you don't have to restart the program after one response. Also, it prints out + * the socket pair the server sees. Run the program via telnet several times and + * compare the socket pairs. + * + * telnet localhost 2317 + * + * If you're sophisticated you can contact the instructor's computer while + * running this program. + * + * telnet [ipNumberOfServerLaptop] 2317 + * + * And have him display the socket pairs he got. + * + * @author mcgredo + */ +public class JacksonTcpServer { + + @SuppressWarnings("ConvertToTryWithResources") + public static void main(String[] args) + { + try { + // ServerSocket waits for a connection from a client. + // Notice that it is outside the loop; ServerSocket + // needs to be made only once. + + System.out.println("TcpServer up and running"); // it helps debugging to put this on console first + ServerSocket serverSocket = new ServerSocket(2317); + + // Server is up and waiting (i.e. "blocked" or paused) + // Loop, infinitely, waiting for client connections. + // Stop the program somewhere else. + while (true) + { + Socket clientConnection = serverSocket.accept(); // block until connected to a client + + // Now hook everything up (i.e. set up the streams), Java style: + OutputStream os = clientConnection.getOutputStream(); + PrintStream ps = new PrintStream(os); + + ps.println("welcome to the Matrix"); // this goes back to client! + + // Print some information locally about the Socket + // connection. This includes the port and IP numbers + // on both sides (the socket pair.) + InetAddress localAddress = clientConnection.getLocalAddress(); + InetAddress remoteAddress = clientConnection.getInetAddress(); + + int localPort = clientConnection.getLocalPort(); + int remotePort = clientConnection.getPort(); + + // My socket pair connection looks like this, to localhost: + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54876 )) + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54881 )) + // + // Why is the first IP/port the same, while the second set has + // different ports? + System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " + + remoteAddress.toString() + ", " + remotePort + " ))"); + + // Notice the use of flush() and close(). Without + // the close() to Socket object may stay open for + // a while after the client has stopped needing this + // connection. Close() explicitly ends the connection. + ps.flush(); + clientConnection.close(); // like it or not, you're outta here! + } + } + catch (IOException e) { + System.out.println("problem with networking" + e); + } + } +}