java中的UDP套接字编程

时间:2014-09-09 06:08:01

标签: java sockets udp

此示例代码如下所示:

public class UDPServer
{

    enter code here
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub
        DatagramSocket serverSocket=new DatagramSocket(9876);
        byte[] receiveData=new byte[1024];
        byte[] sendData=new byte[1024];
        while(true)
        {
            DatagramPacket receivePacket=new DatagramPacket(receiveData, receiveData.length);
            String sentence=new String(receivePacket.getData());
            InetAddress IPAddress=receivePacket.getAddress();
            int port=receivePacket.getPort();
            String capitalizedSentennce=sentence.toUpperCase();
            sendData=capitalizedSentennce.getBytes();
            DatagramPacket sendPacket=new DatagramPacket(sendData, sendData.length,IPAddress,port);
            serverSocket.send(sendPacket);
        }
    }

}
执行时

发出以下错误:

 Exception in thread "main" java.lang.IllegalArgumentException: Port out of range:-1
        at java.net.DatagramPacket.setPort(Unknown Source)
        at java.net.DatagramPacket.<init>(Unknown Source)
        at java.net.DatagramPacket.<init>(Unknown Source)
        at UDPServer.main(UDPServer.java:21)

有人可以帮我解决吗?如果可能的话,请提供其他信息。

1 个答案:

答案 0 :(得分:0)

你忘记收到任何内容receivePacket.所以那里什么都没有。没有端口号,没有源地址,没有数据。