Desktop Only

This site is optimized for desktop viewing. Please access it from your computer.

Socket Code & Live Demo

Study the lab-based Java UDP client and server with full line-by-line explanations and a flow that matches the actual program execution.

java
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.

Interactive Node Diagram

Drag nodes to explore the architecture. The UDP lab uses client port 1000 and server port 2000, where a number is sent and the server responds with whether it is even or odd.

Connection-less Packet Demo

Client127.0.0.1:1000
Connection-less • Even/Odd Datagram • Best Effort
Server127.0.0.1:2000
System Log
13:23:29UDP lab ready: client sends a number to port 2000 and receives an even/odd result on port 1000.