View RSS Feed

Java Socket

Sending Data via a DatagramSocket

Rate this Entry
by , 04-25-2012 at 10:36 PM (1946 Views)
First of all DatagramPacket shall be created for sending data through DatagramSocket Java. It is done as following:
Java Code:
byte[] buffer = new byte[65508];
InetAddress address = InetAddress.getByName("jenkov.com");
DatagramPacket packet = new DatagramPacket(
    buffer, buffer.length, address, 9000);
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.
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:
Java Code:
DatagramSocket datagramSocket = new DatagramSocket();
Send() method shall be called in order to send the data, like this:
Java Code:
datagramSocket.send(packet);

Submit "Sending Data via a DatagramSocket" to Facebook Submit "Sending Data via a DatagramSocket" to Digg Submit "Sending Data via a DatagramSocket" to del.icio.us Submit "Sending Data via a DatagramSocket" to StumbleUpon Submit "Sending Data via a DatagramSocket" to Google

Categories
Tutorial

Comments