Java/PHP/GitLab Fan, Passionate Developer and Loves Teaching

0%

UDP Program to Reverse String

Summary

UDP stands for “User Datagram Protocol

Goal of the program is that a server is present who will be giving service to client to reverse the string entered by client.

Its like a web-service provided by server to client but achieved by sending and receiving packets from both the ends.

Advantages of using UDP

  1. Faster than TCP
  2. Does not restrict you to connection based communication model
  3. Can be used to send large data into smaller packets quickly

Drawbacks of using UDP

  1. Packets sent may not get delivered on time, may get lost in network, may get corrupted, may be sent twice to the receiver
  2. Packets need to be breaked manually
  3. Not reliable

Code

ClientReverse.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package udpprograms;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
*
* @author Rohan Sakhale
*/
public class ClientReverse {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAdress = InetAddress.getLoopbackAddress();
byte [] sendData = new byte[1024];
byte [] receiveData = new byte[1024];
String str = br.readLine();
sendData = str.getBytes();
DatagramPacket dgp = new DatagramPacket(sendData,sendData.length,IPAdress,9999);
clientSocket.send(dgp);
dgp = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(dgp);
str = new String(dgp.getData());
System.out.println(\"Output: \" + str);
clientSocket.close();
br.close();
}
}

ServerReverse.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package udpprograms;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
*
* @author Rohan Sakhale
*/
public class ServerReverse {

public static String reverseInt(int num) {

int ans = 0;
while (num > 0) {
ans = ans * 10 + (num % 10);
num = num / 10;
}
return String.valueOf(ans);
}

public static void main(String[] args) throws Exception {
DatagramSocket dgs = new DatagramSocket(9999);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
DatagramPacket dgp;

dgp = new DatagramPacket(receiveData, receiveData.length);
dgs.receive(dgp);
String str = new String(dgp.getData());
System.out.println(\"Data Received: \" + str);
InetAddress IPAddress = dgp.getAddress();
String ans = ServerReverse.reverseInt(Integer.parseInt(str.toString()));
sendData = ans.getBytes();
dgp = new DatagramPacket(sendData, sendData.length, IPAddress, dgp.getPort());
dgs.send(dgp);


}
}

First server needs to be run & later client.