集册 Java实例教程 接收UDP多播消息的UDP多播套接字

接收UDP多播消息的UDP多播套接字

欢马劈雪     最近更新时间:2020-01-02 10:19:05

500
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
接收UDP组播消息的UDP组播套接字

import java.net.DatagramPacket;

import java.net.InetAddress;

import java.net.MulticastSocket;
/**from 时 代 J     a    v  a - nowjava.com**/

public class Main {

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

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

    MulticastSocket mcSocket = new MulticastSocket(5555);

    System.out.println("Multicast Receiver running at:"

        + mcSocket.getLocalSocketAddress());

    mcSocket.joinGroup(mcIPAddress);


    DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
    /**
    nowjava.com - 时代Java
    **/


    while (true) {

      System.out.println("Waiting for a multicast message...");

      mcSocket.receive(packet);

      String msg = new String(packet.getData(), packet.getOffset(),

          packe
展开阅读全文