简体   繁体   中英

UDP socket programing in java

This sample code shown bellow:

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

}

is giving the following error when executed:

 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)

Can someone help me to resolve it out? Also if possible please provide additional information why it happens.

You forgot to receive anything into the receivePacket. So there is nothing there. No port number, no source address, no data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM