Skip to content

Commit 3341853

Browse files
committed
feat(udp): add DatagramClient and Server with explicit port binding and string reversal response
What - Added two classes demonstrating UDP communication: - DatagramClient: - Creates a DatagramSocket bound to port 2001 (client-side port explicitly set). - Sends "Hello Server:" as a UDP datagram to server on localhost:2000. - Allocates a 1024-byte buffer for response, receives datagram from server, trims, and prints result. - Closes socket after exchange. - Server: - Opens a DatagramSocket bound to port 2000 (server port). - Waits for a datagram from a client, reads content into a String. - Reverses the received string using StringBuilder.reverse(). - Sends reversed string back to the client at localhost:2001. - Closes socket after reply. Why - Demonstrates core concepts of UDP in Java: - DatagramSockets for connectionless communication. - DatagramPackets for message encapsulation. - Explicit port binding (server on 2000, client on 2001) to illustrate bidirectional communication. - Helps understand message boundaries, client-server request/response pattern, and string manipulation in network programming. - Serves as a foundation for building lightweight, low-latency communication systems. How - Client side: - Binds socket to a fixed port (2001) → useful for ensuring server knows where to reply. - Constructs DatagramPacket with msg.getBytes(), message length, server address (InetAddress.getByName("localhost")), and server port (2000). - Sends the packet via ds.send(dp). - Prepares buffer (byte[1024]), wraps in a DatagramPacket, blocks on receive(). - Converts bytes into String using new String(dp.getData()).trim() (trimming trailing nulls). - Prints "From Server Hello: <response>" and closes socket. - Server side: - Creates DatagramSocket on port 2000 to listen for packets. - Receives packet into a fixed buffer, extracts String with new String(dp.getData()).trim(). - Uses StringBuilder.reverse() to reverse the message. - Constructs reply packet with reversed message, sets destination to localhost:2001 (client port). - Sends reply, closes socket. Key considerations / notes - Explicit port binding: - Client uses port 2001 → ensures server knows where to send reply. - In contrast to ephemeral port allocation, this approach is deterministic. - Buffer management: - new String(dp.getData()) reads entire buffer, but .trim() removes trailing whitespace. Better practice: new String(dp.getData(), 0, dp.getLength()). - Character encoding: - Currently uses platform default encoding via getBytes() and new String(byte[]). For portability, specify StandardCharsets.UTF_8. - Single exchange: - Server handles only one packet then exits. To build a persistent service, wrap receive() in a loop. - Blocking I/O: - Both client and server block until data arrives. For timeout handling, configure ds.setSoTimeout(ms) and catch SocketTimeoutException. - Threading: - Current implementation is single-threaded; production-grade servers often handle multiple clients concurrently. - Resource management: - Uses manual socket closing (ds.close()). For safety, prefer try-with-resources or explicit shutdown logic. How to test 1. Run Server (binds to port 2000). java Server Expected output: From Client: Hello Server: 2. Run DatagramClient (binds to port 2001, sends message). java DatagramClient Expected client output: From Server Hello: :revreS olleH Server additionally prints reversed message was sent. Real-life applications - Simple request/response protocols over UDP (e.g., DNS-style queries). - Quick-and-lightweight text-based message exchange for demos. - Learning environment to understand connectionless datagram transport. Future improvements - Replace .trim() with new String(dp.getData(), 0, dp.getLength(), UTF_8). - Convert server to loop for continuous service. - Add logging, configurable host/port, and better error handling. - Extend to handle multiple message types or structured payloads. - Implement retry/ACK mechanism for reliability in lossy networks. Files added - DatagramClient.java — sends and receives UDP packets via explicit client port. - Server.java — listens on fixed server port, reverses client message, replies. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 3cddd8f commit 3341853

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

Section27NetworkProgramming/DataGramReverseEchoServer/src/DatagramClient.java

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,17 @@ public static void main(String[] args)throws Exception{
77

88
String msg = "Hello Server: ";
99

10-
//Array of Bytes. That you want to send using a datagram packets.
10+
//Array of Bytes. That you want to send using a datagram packet.
1111
DatagramPacket dp = new DatagramPacket(msg.getBytes(),msg.length(),InetAddress.getByName("localHost"),2000);
1212
//msg.length = What is the length of the array of the bytes that is msg.length.
1313
//Inet = Ip address you want to send.
1414

15-
//Now lets the this above packets to the server.
15+
//Now lets this above packet to the server.
1616
ds.send(dp);
17-
//Client has send the packet.
17+
//Client has sent the packet.
1818

19-
byte b[]=new byte[1024]; //receiving the size of the packets from the Server.
19+
byte b[]=new byte[1024];
20+
//receiving the size of the packets from the Server.
2021
//For received the packets and display it from the server.
2122
dp=new DatagramPacket(b,1024);
2223

@@ -29,32 +30,34 @@ public static void main(String[] args)throws Exception{
2930
ds.close();
3031
}
3132
}
33+
3234
class Server{
3335
public static void main(String[] args)throws Exception {
3436
//Server Address and port number needed.
3537
DatagramSocket ds = new DatagramSocket(2000);
3638

37-
//First done. next what server has to do receiving a packet.
39+
//First done. next what the server has to do is receive a packet.
3840
byte b[]=new byte[1024];
3941
//Packet is received
4042
DatagramPacket dp = new DatagramPacket(b,1024);
4143

4244
ds.receive(dp);
4345

4446
//Now it has to create a string and reverse the string from
45-
//that receiving the packets from client.
47+
//that receiving the packets from a client.
4648

4749
String msg = new String(dp.getData()).trim();
4850
System.out.println("From Client: "+msg);
4951

50-
//Reverse
52+
//Reverse.
5153
StringBuilder sb = new StringBuilder(msg);
5254
sb.reverse();
53-
msg = sb.toString(); //getting a string.
55+
msg = sb.toString();
56+
//getting a string.
5457

55-
//This msg it sending it to the Client using a datagram packets.
58+
//This msg it sending it to the Client using a datagram packet.
5659
dp = new DatagramPacket(msg.getBytes(),msg.length(),InetAddress.getByName("localHost"),2001);
5760
ds.send(dp);
5861
ds.close();
5962
}
60-
}
63+
}

0 commit comments

Comments
 (0)