通过UDP发送DatagramPacket

时间:2016-06-04 14:44:51

标签: java udp datagram

我正在尝试通过UDP发送一些数据。这是我的代码:

public class UDP {
public static void main(String args[]) throws IOException { 
    InetAddress inetAddress = InetAddress.getByName("239.255.42.99");
    int PORT = 2225;
    int BUFFER_SIZE = 10;
    DatagramSocket datagramSocket = new DatagramSocket(PORT, inetAddress);
    byte[] buf = new byte[BUFFER_SIZE];
    String message = "0123456789";
    buf = message.getBytes();
    DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);

    datagramPacket = new DatagramPacket(buf, buf.length);
    datagramPacket.setAddress(inetAddress);
    datagramPacket.setPort(PORT);

    datagramSocket.send(datagramPacket);
    datagramSocket.setSoTimeout(1010);
}
}

我有这个错误:

Exception in thread "main" java.io.IOException: Invalid argument
at java.net.PlainDatagramSocketImpl.send(Native Method)
at java.net.DatagramSocket.send(DatagramSocket.java:698)
at UDP.main(UDP.java:21)

任何人都知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

以这种方式尝试:

public static void main(String args[]) throws IOException {
    InetAddress inetAddress = InetAddress.getByName("239.255.42.99");
    int PORT = 2225;
    int BUFFER_SIZE = 10;
    DatagramSocket datagramSocket = new DatagramSocket();
    byte[] buf = new byte[BUFFER_SIZE];
    String message = "0123456789";
    buf = message.getBytes();
    DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, inetAddress, PORT);

    datagramSocket.send(datagramPacket);
    datagramSocket.setSoTimeout(1010);
}