Java Tutorial/Network/MulticastSocket

Материал из Java эксперт
Версия от 05:03, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Joining a Multicast Group

import java.net.InetAddress;
import java.net.MulticastSocket;
public class Main {
  public static void main(String[] argv) throws Exception {
    String groupName = "groupName";
    int port = 1024;
    MulticastSocket msocket = new MulticastSocket(port);
    InetAddress group = InetAddress.getByName(groupName);
    msocket.joinGroup(group);
  }
}





Multicast Sender

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MainClass {
  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();
    ms.joinGroup(ia);
    for (int i = 1; i < 10; i++) {
      ms.send(dp, ttl);
    }
    ms.leaveGroup(ia);
    ms.close();
  }
}





Multicast Sniffer

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MainClass {
  public static void main(String[] args) throws Exception {
    int port = 0;
    InetAddress group = InetAddress.getByName("127.0.0.1");
    MulticastSocket ms = new MulticastSocket(port);
    ms.joinGroup(group);
    byte[] buffer = new byte[8192];
    while (true) {
      DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
      ms.receive(dp);
      String s = new String(dp.getData());
      System.out.println(s);
    }
    // ms.leaveGroup(group);
    // ms.close();
  }
}





Receiving from a Multicast Group

import java.net.DatagramPacket;
import java.net.MulticastSocket;
public class Main {
  public static void main(String[] argv) throws Exception {
    MulticastSocket msocket = new MulticastSocket(9999);
    byte[] inbuf = new byte[1024];
    DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
    msocket.receive(packet);
    // Data is now in inbuf
    int numBytesReceived = packet.getLength();
  }
}





Sending to a Multicast Group

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] outbuf = new byte[1024];
    int port = 1234;
    DatagramSocket socket = new DatagramSocket();
    InetAddress groupAddr = InetAddress.getByName("8.1.2.3");
    DatagramPacket packet = new DatagramPacket(outbuf, outbuf.length, groupAddr, port);
    socket.send(packet);
  }
}