package UdpMulticastHttpExamples; import java.io.*; import java.net.*; import java.nio.ByteBuffer; /** * 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. * * @author mcgredo * @author brutzman */ public class UdpReceiver { public static final int SENDING_PORT = 1414; 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; int packetCount = 0; try { System.out.println(UdpReceiver.class.getName() + " started..."); // Create a UDP socket udpSocket = new DatagramSocket(RECEIVING_PORT); udpSocket.setReceiveBufferSize(1500); udpSocket.setBroadcast(false); // we're just receiving here ByteBuffer buffer = ByteBuffer.allocate(1500); DatagramPacket receivePacket = new DatagramPacket(buffer.array(), buffer.capacity()); float first, second; // You need a new receiving packet to read from every packet received while (true) { udpSocket.receive(receivePacket); // What happens if you read an integer? Two double values? *** first = buffer.getFloat(); // alternatives: readFloat(); readInt(); dis.readUTF(); second = buffer.getFloat(); buffer.clear(); System.out.println("first value: " + first + " second value: " + second + " packet count = " + ++packetCount); } } catch(IOException e) { System.err.println("Problem with UdpReceiver, see exception trace:"); System.err.println(e); } finally { if (udpSocket != null) udpSocket.close(); } } }