// UDPReceive2.java
// This example is from the book _Java in a Nutshell_ by David Flanagan.
// Written by David Flanagan.  Copyright (c) 1996 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
// Modified by tsaiwn@csie.nctu.edu.tw to fix International problem

import java.io.*;
import java.net.*;
 // This program waits to receive Datagrams sent to port 6010.  
// When it receives one, it displays the sending host and port, 
 // and prints the contents of the Datagram as a string.
 /// ///  classes used: DatagramSocket, DatagramPacket
public class UDPReceive2 {
    static final int port = 6010;
    public static void main(String args[]) throws Exception
    {
        byte[] buffer = new byte[1600];
        String s;
       // Create a socket to listen on the port. (use receive(packet); )
        DatagramSocket socket = new DatagramSocket(port);
        
        for(;;) { // Create a packet with an empty buffer to receive data
            // Bug workaround: create a new packet each time through the loop.
            // If we create the packet outside of this loop, then it seems to
            // loose track of its buffer size, and incoming packets are 
            // truncated.
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);  // Wait to receive a Datagram
             // Convert the contents to a string; note the Charset problem
            ///s = new String(buffer, 0, 0, packet.getLength()); //deprecated
            //s = new String(buffer, 0, packet.getLength(),"Big5"); //by tsaiwn
            s = new String(buffer, 0, packet.getLength()); // default Charset
             // Note that 網路上流動是 Byte Stream, Not character
            // And display them on the Console
            System.out.println("UDPReceive: received from " + 
                       packet.getAddress().getHostName() + ":" +
                       packet.getPort() + ": " + s);
        } // for
    } // main
}
