public boolean send(String msg, String bindAddr, int bindPort) { try { MulticastSocket msock; if ((bindAddr) != null && (0 < bindPort)) { msock = new MulticastSocket(null); msock.bind(new InetSocketAddress(bindAddr, bindPort)); } else msock = new MulticastSocket(); DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), ssdpMultiGroup); // Thnaks for Tho Beisch (11/09/04) msock.setTimeToLive(4); msock.send(dgmPacket); msock.close(); } catch (Exception e) { Debug.warning(e); return false; } return true; }
void closeMulticastSocket() { if (mcast_sock != null) { try { if (mcast_addr != null) { // by sending a dummy packet the thread will be awakened sendDummyPacket(mcast_addr.getIpAddress(), mcast_addr.getPort()); Util.sleep(300); mcast_sock.leaveGroup(mcast_addr.getIpAddress()); } mcast_sock.close(); // this will cause the mcast receiver thread to break out of its loop mcast_sock = null; if (Trace.trace) { Trace.info("UDP.closeMulticastSocket()", "multicast socket closed"); } } catch (IOException ex) { } mcast_addr = null; } }
public static void main(String[] args) throws IOException { MulticastSocket socket = new MulticastSocket(4446); InetAddress address = InetAddress.getByName("230.0.0.1"); socket.joinGroup(address); DatagramPacket packet; // get a few quotes for (int i = 0; i < 5; i++) { byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String received = new String(packet.getData(), 0, packet.getLength()); System.out.println("Quote of the Moment: " + received); } socket.leaveGroup(address); socket.close(); }