Skip to content
Snippets Groups Projects
UdpReceiver.java 1.96 KiB
package UdpMulticastHttpExamples;

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.
 * 
 * @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
     */
    public static void main(String[] args) 
    {
        try
        {
            System.out.println("UdpReceiver started...");
            // Create a UDP socket
            DatagramSocket udpSocket = new DatagramSocket(RECEIVING_PORT);
            
            // You need a new receiving packet to read from every packet received
            while (true)
            {
                byte[] receiveBuffer = new byte[1500];
                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
                udpSocket.receive(receivePacket);
                
                // Decode the contents by extracting the data from the packet
                ByteArrayInputStream bais = new ByteArrayInputStream(receivePacket.getData());
                DataInputStream dis = new DataInputStream(bais);
                
                // What happens if you read an integer? Two double values? ***
                float  first = dis.readFloat(); // alternatives: readFloat(); readInt(); dis.readUTF(); 
                float second = dis.readFloat();
                System.out.println("first value: " + first + " second value: " + second);
            }
        }
        catch(IOException e)
        {
            System.out.println("Problem with UdpReceiver, see exception trace:");
            System.out.println(e);
        }
    }
}