/Users/lyon/j4p/src/net/multicast/McastUtil.java

1    package net.multicast; 
2     
3    import java.io.IOException; 
4    import java.net.DatagramPacket; 
5    import java.net.InetAddress; 
6    import java.net.MulticastSocket; 
7    import java.net.SocketException; 
8     
9    public class McastUtil { 
10       private int port = 2435; 
11       private InetAddress inetAddress; 
12       private MulticastSocket mcastSocket; 
13       byte buf[] = new byte[100000]; 
14    
15    
16       public McastUtil(int port) { 
17           try { 
18               this.port = port; 
19               inetAddress = Utils.getInetAddress(); 
20               mcastSocket = 
21                       Utils.getMulticastSocket(port, inetAddress); 
22           } catch (Exception e) { 
23               e.printStackTrace(); 
24           } 
25       } 
26    
27       public void setLoopBack(boolean b) { 
28           try { 
29               mcastSocket.setLoopbackMode(b); 
30           } catch (SocketException e) { 
31               e.printStackTrace(); 
32           } 
33       } 
34    
35       /** 
36        * Invocation blocks the callers' thread of execution, 
37        * so invoke inside of another thread, in a loop. 
38        * 
39        * @return 
40        * @throws IOException 
41        */ 
42       public byte[] getBytes() throws IOException { 
43           DatagramPacket recv = new DatagramPacket(buf, buf.length); 
44           mcastSocket.receive(recv); 
45           buf = recv.getData(); 
46           byte b[] = new byte[recv.getLength()]; 
47           for (int i=0; i < b.length; i++) 
48               b[i] = buf[i]; 
49           return b; 
50       } 
51    
52       public void sendBytes(byte b[]) throws IOException { 
53           DatagramPacket dp = new DatagramPacket(b, 
54                   b.length, 
55                   inetAddress, 
56                   port); 
57           mcastSocket.send(dp); 
58       } 
59    
60       public int getPort() { 
61           return port; 
62       } 
63    
64       public InetAddress getInetAddress() { 
65           return inetAddress; 
66       } 
67    
68       public MulticastSocket getMcastSocket() { 
69           return mcastSocket; 
70       } 
71   } 
72