import java.io.*; import java.util.*; import java.net.*; public class TestReceiveThread extends Thread { //private DatagramSocket socket; private MulticastSocket socket; private byte [] buf; private InetAddress group; public static final String GROUP_ADDR = "239.255.255.254"; public static final int PORTNUM = 8019; public TestReceiveThread() { this("TestReceiveThread"); } public TestReceiveThread(String name) { super(name); try { //socket = new DatagramSocket(PORTNUM); socket = new MulticastSocket(PORTNUM); } catch (SocketException se) { se.printStackTrace(); } catch (SecurityException se2) { se2.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } /* try { System.out.println("Broadcast: " + socket.getBroadcast()); } catch (SocketException se) { se.printStackTrace(); } try { socket.setBroadcast(true); } catch (SocketException se) { se.printStackTrace(); } */ try { buf = new byte[socket.getSendBufferSize()]; } catch (SocketException se) { se.printStackTrace(); } group = null; try { group = InetAddress.getByName(GROUP_ADDR); } catch (UnknownHostException uhe) { uhe.printStackTrace(); System.exit(1); } try { socket.joinGroup(group); } catch (IOException ioe) { ioe.printStackTrace(); } } public void run() { boolean keepRunning = true; while (keepRunning) { try { DatagramPacket packet = new DatagramPacket(buf, buf.length); System.out.println("Receiving... "); socket.receive(packet); String testMsg = new String(packet.getData()); System.out.println("Message received: " + testMsg); } catch (IOException e) { e.printStackTrace(); keepRunning = false; } } try { socket.leaveGroup(group); } catch (IOException ioe) { ioe.printStackTrace(); } socket.close(); } }