1import java.io.*;
2import java.net.*;
3public class UDPClient {
4 public static void main(String args[]) {
5 try {
6 DatagramSocket datagramSocket = new DatagramSocket(1000);
7 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8 System.out.println("Enter a number : " );
9 String num = br.readLine();
10 byte b[] = new byte[1024];
11 b = num.getBytes();
12 DatagramPacket dp = new DatagramPacket(b, b.length, InetAddress.getLocalHost(), 2000);
13 datagramSocket.send(dp);
14 byte b1[] = new byte[1024];
15 DatagramPacket dp1 = new DatagramPacket(b1, b1.length);
16 datagramSocket.receive(dp1);
17 String str = new String(dp1.getData(), 0, dp1.getLength());
18 System.out.println(str);
19 } catch (Exception e) {
20 e.printStackTrace();
21 }
22 }
23}
Line Explanation
Hover over a line to see its explanation.
Highlighted Lines
6Creates the client UDP socket and binds it to port 1000, which is where the server will send its reply.
7Creates a buffered reader connected to standard input so the user can type a number from the keyboard.
9Reads the user's typed input as a string from the keyboard.
11Converts the typed number string into bytes because the datagram transports bytes, not String objects.
12Builds a datagram packet containing the number, addressed to the local machine on server port 2000.
13Sends the number packet to the UDP server. No connection setup or handshake happens before this send.
15Creates an empty datagram packet wrapper that will receive the reply from the server.
16Blocks the client until the server sends back the result datagram to port 1000.
17Converts the received response bytes into a proper string using only the actual length of the packet data.