All pastes #248387 Raw Edit

Untitled

public text v1 · immutable
#248387 ·published 2006-11-14 16:29 UTC
rendered paste body
Sender :
public static void main(String argv[]) {
 
    InetAddress mcAddress=null;  /* multicast address */
    int mcPort=0;                /* multicast port */
    int ttl=1;                   /* time to live */
    BufferedReader stdin;        /* input from keyboard */
    String sendString;           /* string to be sent */
    byte[] sendBytes;            /* bytes to be sent */

try {
       
      /* instantiate a MulticastSocket */
      MulticastSocket sock = new MulticastSocket();

      /* set the time to live */
      sock.setTimeToLive(ttl); // Java 1.0/1.1 use setTTL()

      /* prepare to read from the keyboard input */
      stdin=new BufferedReader(new InputStreamReader(System.in));

      System.out.println("Begin typing (return to send," + 
                         " ctrl-C to quit):");

      while ((sendString=stdin.readLine()) != null) {

        /* convert keyboard input to bytes */
        sendBytes=sendString.getBytes();

        /* populate the DatagramPacket */
        DatagramPacket packet = new DatagramPacket(sendBytes,                                 sendBytes.length, mcAddress, mcPort);

        /* send the packet */
        sock.send(packet);
      }
      sock.close();

    } catch (IOException e) {
      System.err.println(e.toString());
      System.exit(1);
    }
  }

Reciever
  try {

      /* instantiate a MulticastSocket */
      MulticastSocket sock = new MulticastSocket(mcPort);

      /* set the address reuse option */
      sock.setReuseAddress(true); // Java 1.4 and higher

      /* join the multicast group */
      sock.joinGroup(mcAddress);

      while (!done) {  /* loop forever */
         
        /* create a new DatagramPacket with an empty buffer */
        byte[] buf = new byte[MAX_LEN];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        /* wait to receive packet into the DatagramPacket instance */
        sock.receive(packet);

        /* output the data from the packet received */
        System.out.println("Received " + packet.getLength() +
            " bytes from " + packet.getAddress() + ": " 
            + new String(packet.getData(),0,packet.getLength()));
      }

      sock.leaveGroup(mcAddress);
      sock.close();

    } catch (IOException e) {
      System.err.println(e.toString());
      System.exit(1);
    }
  }