3

我正在使用以下代码Hello, world!使用 Java 发送到多播组。

InetSocketAddress sa = new InetSocketAddress("239.0.0.1", 12345);
MulticastSocket s = new MulticastSocket(sa);
s.setTimeToLive(255);
s.joinGroup(sa.getAddress());

byte[] sbuf = "Hello, world!".getBytes();
DatagramPacket sp = new DatagramPacket(sbuf, sbuf.length, sa);
s.send(sp);

byte[] rbuf = new byte[1024];
DatagramPacket rp = new DatagramPacket(rbuf, rbuf.length);
s.receive(rp);

System.out.format("Received \"%s\".\n", new String(rbuf));

s.leaveGroup(sa.getAddress());
s.close();

出于某种原因,代码总是抛出这样的异常:

java.io.Exception: Invalid argument
    at java.net.PlainDatagramSocketImpl.send(Native Method)
    at java.net.DatagramSocket.send(...)
    at ...

为什么是这样?我该如何解决?

4

2 回答 2

-1

获取数据:

            InetAddress group;
            int port;
            group = InetAddress.getByName("239.0.0.1");
            port = Integer.parseInt("12345");

            //create Multicast socket to to pretending group
            MulticastSocket s = new MulticastSocket(port);
            s.joinGroup(group);

while(running){

            s.receive(pkt);

            System.out.println();

            String msg_rec;

            msg_rec = new String(pkt.getData(), 0, pkt.getLength());


            System.out.println("(FROM:" + pkt.getAddress()+ ") "+ msg_rec);

            System.out.println();

        }

发送数据:

String msgToSend = "Hello, world!";

            dgram = new DatagramPacket(msgToSend.getBytes(), msgToSend.length(), group ,port);
            s.send(dgram);  
于 2012-12-28T22:15:18.667 回答
-1

您正在调用send()一个未连接DatagramSocket且不DatagramPacket包含目标地址的端口:端口。所以无处可寄。如果您的意思是发送到多播地址,则需要通过执行第一句中提到的任何一项来说明。加入群组不会这样做:它只会影响接收。

于 2012-12-29T00:13:33.957 回答