Source of MulticastSender.java


  1: // Fig. 24.23: MulticastSender.java
  2: // MulticastSender broadcasts a chat message using a multicast datagram.
  3: package com.deitel.messenger.sockets.server;
  4: 
  5: import java.io.IOException;
  6: import java.net.DatagramPacket;
  7: import java.net.DatagramSocket;
  8: import java.net.InetAddress;
  9: 
 10: import static com.deitel.messenger.sockets.SocketMessengerConstants.*;
 11: 
 12: public class MulticastSender implements Runnable
 13: {   
 14:    private byte[] messageBytes; // message data
 15:    
 16:    public MulticastSender( byte[] bytes ) 
 17:    { 
 18:       messageBytes = bytes; // create the message
 19:    } // end MulticastSender constructor
 20: 
 21:    // deliver message to MULTICAST_ADDRESS over DatagramSocket
 22:    public void run() 
 23:    {
 24:       try // deliver message
 25:       {         
 26:          // create DatagramSocket for sending message
 27:          DatagramSocket socket = 
 28:             new DatagramSocket( MULTICAST_SENDING_PORT );
 29:          
 30:          // use InetAddress reserved for multicast group
 31:          InetAddress group = InetAddress.getByName( MULTICAST_ADDRESS );
 32:          
 33:          // create DatagramPacket containing message
 34:          DatagramPacket packet = new DatagramPacket( messageBytes, 
 35:             messageBytes.length, group, MULTICAST_LISTENING_PORT );
 36:          
 37:          socket.send( packet ); // send packet to multicast group
 38:          socket.close(); // close socket
 39:       } // end try
 40:       catch ( IOException ioException ) 
 41:       { 
 42:          ioException.printStackTrace();
 43:       } // end catch
 44:    } // end method run
 45: } // end class MulticastSender
 46: 
 47: 
 48: /**************************************************************************
 49:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 50:  * Pearson Education, Inc. All Rights Reserved.                           *
 51:  *                                                                        *
 52:  * DISCLAIMER: The authors and publisher of this book have used their     *
 53:  * best efforts in preparing the book. These efforts include the          *
 54:  * development, research, and testing of the theories and programs        *
 55:  * to determine their effectiveness. The authors and publisher make       *
 56:  * no warranty of any kind, expressed or implied, with regard to these    *
 57:  * programs or to the documentation contained in these books. The authors *
 58:  * and publisher shall not be liable in any event for incidental or       *
 59:  * consequential damages in connection with, or arising out of, the       *
 60:  * furnishing, performance, or use of these programs.                     *
 61:  *************************************************************************/