集册 Java实例教程 创建多播套接字

创建多播套接字

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

504
创建MulticastSocket

import java.io.*;

import java.net.*;

import java.util.*;
/**
nowjava - 时代Java 提供 
**/


public class MulticastClient {


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


        MulticastSocket socket = new MulticastSocket(4446);

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

        socket.joinGroup(address);

        /*
         from N o w  J a v a  . c o m 
        */

        DatagramPacket packet;


        // get a few quotes

        for (int i = 0; i < 5; i++) {


            byte[] buf = new byte[256];

            packet = new DatagramPacket(buf, buf.length);

            socket.receive(packet);


            String received = new String(packet.getData(), 0,

                    packet.getLength());

            System.out.println("Quote of the Moment: " + received);

        }


        socket.leaveGroup(address);

        socket.close();

    }


}


展开阅读全文