Sending Data via a DatagramSocket
by, 04-25-2012 at 10:36 PM (1779 Views)
First of all DatagramPacket shall be created for sending data through DatagramSocket Java. It is done as following:
The byte array or byte buffer is that data which is required to be sent, in UDP datagram. Above mentioned buffer’s length (65508 bytes) is that maximum data amount which can be sent in single UDP packet.Java Code:byte buffer = new byte; InetAddress address = InetAddress.getByName("jenkov.com"); DatagramPacket packet = new DatagramPacket( buffer, buffer.length, address, 9000);
DatagramPacket constructor’s length is that data length present in buffer to be sent. Data present in buffer, after that data amount, is ignored.
The InetAddress instance consists of the node address so that it could send out the UDP packets. The InetAddress class presents internet address or IP address. An InetAddress instance is returned by the getByName() method along with the IP address which matches with the provided host name.
TCP and UDP ports are not same thing. Different processes listening could be present at a computer like Port 80 is present in TCP as well as UDP at the same time.
One needs to create the DatagramSocket in order to send out DatagramPacket. This is done as following:
Send() method shall be called in order to send the data, like this:Java Code:DatagramSocket datagramSocket = new DatagramSocket();