Java API Tutorial - Java MulticastSocket(int port) Constructor








Syntax

MulticastSocket(int port) constructor from MulticastSocket has the following syntax.

public MulticastSocket(int port)    throws IOException

Example

In the following code shows how to use MulticastSocket.MulticastSocket(int port) constructor.

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
//from   ww  w. j av a  2 s .  c  om
public class Main {

  public static void main(String[] args) throws Exception {

    int port = 0;
    byte ttl = (byte) 1;

    InetAddress ia = InetAddress.getByName("127.0.0.1");

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);

    MulticastSocket ms = new MulticastSocket(8080);
    ms.joinGroup(ia);
    for (int i = 1; i < 10; i++) {
      ms.send(dp, ttl);
    }
    ms.leaveGroup(ia);
    
    
    ia = ms.getInterface();
    System.out.println(ia);
    
    ms.close();
  }

}