集册 Java实例教程 使用多播套接字创建多播接收器

使用多播套接字创建多播接收器

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

473
使用MulticastSocket创建多播接收器
//from 时 代 J a v a 公 众 号 - N o w J a v  a . c o m

import java.io.*;

import java.net.*;


public class MulticastReceiver {

  public static void main(String[] args) {

    DatagramPacket inPacket = null;

    byte[] inBuf = new byte[256];

    try {

      //Prepare to join multicast group

      MulticastSocket socket = new MulticastSocket(8888);

      InetAddress address = InetAddress.getByName("224.2.2.3");

      socket.joinGroup(address);


      while (true) {

        inPacket = new DatagramPacket(inBuf, inBuf.length);

        socket.receive(inPacket);

        String msg = new String(inBuf, 0, inPacket.getLength());/** from N o  w  J a v a . c o m - 时  代  Java**/

        System.out.println(
展开阅读全文