Send udp packet in java

Java Networking: UDP DatagramSocket

DatagramSocket‘s are Java’s mechanism for network communication via UDP instead of TCP. UDP is still layered ontop of IP. You can use Java’s DatagramSocket both for sending and receiving UPD datagrams.

UDP vs. TCP

UDP works a bit differently from TCP. When you send data via TCP you first create a connection. Once the TCP connection is established TCP guarantess that your data arrives at the other end, or it will tell you that an error occurred.

With UDP you just send packets of data (datagrams) to some IP address on the network. You have no guarantee that the data will arrive. You also have no guarantee about the order which UDP packets arrive in at the receiver. This means that UDP has less protocol overhead (no stream integrity checking) than TCP.

UDP is appropriate for data transfers where it doesn’t matter if a packet is lost in transition. For instance, imagine a transfer of a live TV-signal over the internet. You want the signal to arrive at the clients as close to live as possible. Therefore, if a frame or two are lost, you don’t really care. You don’t want the live broadcast to be delayed just to make sure all frames are shown at the client. You’d rather skip the missed frames, and move directly to the newest frames at all times.

This could also be the case with a surveillance camera broadcasting over the internet. Who cares what happened in the past, when you are trying to monitor the present. You don’t want to end up being 30 seconds behind reality, just because you want to show all frames to the person monitoring the camera. It is a bit different with the storage of the camera recordings. You may not want to lose a single frame when recording the images from the camera to disk. You may rather want a little delay, than not have those frames to go back and examine, if something important occurs.

Sending Data via a DatagramSocket

To send data via Java’s DatagramSocket you must first create a DatagramPacket . Here is how that is done:

byte[] buffer = new byte[65508]; InetAddress address = InetAddress.getByName("jenkov.com"); DatagramPacket packet = new DatagramPacket( buffer, buffer.length, address, 9000);

The byte buffer (the byte array) is the data that is to be sent in the UDP datagram. The length of the above buffer, 65508 bytes, is the maximum amount of data you can send in a single UDP packet.

Читайте также:  Python tkinter размеры окна

The length given to the DatagramPacket constructor is the length of the data in the buffer to send. All data in the buffer after that amount of data is ignored.

The InetAddress instance contains the address of the node (e.g. server) to send the UDP packet to. The InetAddress class represents an IP address (Internet Address). The getByName() method returns an InetAddress instance with the IP address matching the given host name.

The port parameter is the UDP port the server to receiver the data is listeing on. UDP and TCP ports are not the same. A computer can have different processes listening on e.g. port 80 in UDP and in TCP at the same time.

To send the DatagramPacket you must create a DatagramSocket targeted at sending data. Here is how that is done:

DatagramSocket datagramSocket = new DatagramSocket();

To send data you call the send() method, like this:

DatagramSocket datagramSocket = new DatagramSocket(); byte[] buffer = "0123456789".getBytes(); InetAddress receiverAddress = InetAddress.getLocalHost(); DatagramPacket packet = new DatagramPacket( buffer, buffer.length, receiverAddress, 80); datagramSocket.send(packet);

Receiving Data via a DatagramSocket

Receiving data via a DatagramSocket is done by first creating a DatagramPacket and then receiving data into it via the DatagramSocket ‘s receive() method. Here is an example:

DatagramSocket datagramSocket = new DatagramSocket(80); byte[] buffer = new byte[10]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); datagramSocket.receive(packet);

Notice how the DatagramSocket is instantiated with the parameter value 80 passed to its constructor. This parameter is the UDP port the DatagramSocket is to receive UDP packets on. As mentioned earlier, TCP and UDP ports are not the same, and thus do not overlap. You can have two different processes listening on both TCP and UDP port 80, without any conflict.

Second, a byte buffer and a DatagramPacket is created. Notice how the DatagramPacket has no information about the node to send data to, as it does when creating a DatagramPacket for sending data. This is because we are going to use the DatagramPacket for receiving data, not sending it. Thus no destination address is needed.

Finally the DatagramSocket ‘s receive() method is called. This method blocks until a DatagramPacket is received.

The data received is located in the DatagramPacket ‘s byte buffer. This buffer can be obtained by calling:

byte[] buffer = packet.getData();

How much data was received in the buffer is up to you to find out. The protocol you are using should specify either how much data is sent per UDP packet, or specify an end-of-data marker you can look for instead.

Читайте также:  Тильда вставить свой javascript

A real server program would probably call the receive() method in a loop, and pass all received DatagramPacket ‘s to a pool of worker threads, just like a TCP server does with incoming connections (see Java Multithreaded Servers for more details).

Источник

Working with UDP DatagramSockets in Java

DatagramSockets are Java’s mechanism for network communication via UDP instead of TCP. Java provides DatagramSocket to communicate over UDP instead of TCP. It is also built on top of IP. DatagramSockets can be used to both send and receive packets over the Internet.

One of the examples where UDP is preferred over TCP is the live coverage of TV channels. In this aspect, we want to transmit as many frames to live audience as possible not worrying about the loss of one or two frames. TCP being a reliable protocol add its own overhead while transmission.
Another example where UDP is preferred is online multiplayer gaming. In games like counter-strike or call of duty, it is not necessary to relay all the information but the most important ones. It should also be noted that most of the applications in real life uses careful blend of both UDP and TCP; transmitting the critical data over TCP and rest of the data via UDP.

This article is a simple implementation of one-sided client-server program wherein the client sends messages to server and server just prints it until the client sends “bye”.

Java Datagram programming model Steps

  1. Creation of DatagramSocket:- First, a datagramSocket object is created to carry the packet to the destination and to receive it whenever the server sends any data. To create a datagramSocket following constructors can be used:
  2. protected DatagramSocket DatagramSocket():
Syntax: public DatagramSocket() throws SocketException Creates a datagramSocket and binds it to any available port on local machine. If this constructor is used, the OS would assign any port to this socket.
Syntax: public DatagramSocket(int port) throws SocketException Parameters: port - port to which socket is to be bound Throws: SocketException - If the socket cannot be bound to the specific local port. Creates a DatagramSocket and binds to the specified port on the local machine.
Syntax: public DatagramPacket(byte buf[], int length) Parameters: buf - the packet data. length - the packet data length. Constructs a DatagramPacket for receiving the data of length length in the byte array buf.
Syntax: void send(DatagramPacket packet) throws SocketException Parameters: packet - Datagrampacket to send. Throws: SocketException - If there is an error in binding. IllegalArgumentException - if address is not supported by the socket.
Syntax: void receive(DatagramPacket packet) throws SocketException Parameters: packet - Datagrampacket to receive from this socket. Throws: SocketException - If there is an error in binding. IllegalArgumentException - if address is not supported by the socket.

Client Side Implementation

Java

Server side Implementation

Java

In a nutshell, we can summarize the steps of sending and receiving data over UDP as follows:-

  1. For sending a packet via UDP, we should know 4 things, the message to send, its length, ipaddress of destination, port at which destination is listening.
  2. Once we know all these things, we can create the socket object for carrying the packets and packets which actually possess the data.
  3. Invoke send()/receive() call for actually sending/receieving packets.
  4. Extract the data from the received packet.
Client:- Hello Client:- I am client. . Client:- bye Client sent bye. EXITING

Note:- In order to test the above programs on the system, Please make sure that you run the server program first and then the client one. Make sure you are in the client console and from there keep on typing your messages each followed with a carriage return. Every time you send a message you will be redirected to the server console depending on your environment settings. If not redirected automatically, switch to server console to make sure all your messages are received. Finally to terminate the communication, type «bye» (without quotes) and hit enter.

As an enthusiastic reader you should also try and implement a two way chat application wherein the server will be able to respond to messages as and when he likes.

This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Источник

Оцените статью