gpt4 book ai didi

Java UDP 多播 - 奇怪的异常

转载 作者:行者123 更新时间:2023-12-03 21:45:39 24 4
gpt4 key购买 nike

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

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 ...

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

最佳答案

获取数据:

            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);

关于Java UDP 多播 - 奇怪的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14076379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com