Network Programming, UDP Echo Client

Network Programming, UDP Echo Client

When network testing, it is useful to have a client program connects to a UDP server and gets an echo of a text string that you send to the server:

 import*;import*;import java.util.*;class SocketUdpEcho01{	public static void main(String[] args){		String server = "";		int port = 7; //echo port		String msg = "This is a UDP echo test";		try{    			//Convert the message to a byte array			byte[] udpMsg = msg.getBytes();			InetAddress addr = InetAddress.getByName(server);			//Create a packet			DatagramPacket packet = 				new DatagramPacket(udpMsg,udpMsg.length,addr,port);			//Get a datagram socket to send the message			DatagramSocket datagramSocket = new DatagramSocket();			//Send the message			datagramSocket.send(packet);      			//Overwrite the msg in the packet to confirm that			//an echo is really received			byte[] dataArray = packet.getData();			for(int cnt = 0; cnt < packet.getLength(); cnt++)				dataArray[cnt] = 'x';			//Display overwritten version			System.out.println(new String(packet.getData()));			//Receive the echo into the same packet.			datagramSocket.receive(packet);			//Display the echo			System.out.println(new String(packet.getData()));			datagramSocket.close();		}//end try		catch(UnknownHostException e){			System.out.println(e);			System.out.println(					"Connection Failure. Are you online?");		}//end catch UnknownHostException    		catch(SocketException e){System.out.println(e);}		catch(IOException e){System.out.println(e);}    	}//end main}//end class SocketUdpEcho01

After editing your favorite Web server name into the string named server, the program should display:


If another message is displayed, you should try another server. This code was tested using JDK 1.1.6 under Win95.

See also  5 Tips for Working With an Onsite Interpreter

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist