Server to Client using UDP Example Java

Server to Client UDP Java

byte arr1[] = new byte[100];

A byte array object arr1 is created of size 100 bytes sufficient to store the time message sent by the server.

dpack = new DatagramPacket(arr1, arr1.length);

The byte array object arr1 is passed to the DatagramPacket constructor. The receive() method of DatagramSocket receives the data sent by the server into the byte array object arr1.

byte arr2[] = dpack.getData();
String str = new String(arr2);

Now the DatagramPacket object dpack contains the complete message sent by the server. It is in the form of byte array. getData() method of DatagramPacket returns a byte array that contains the message. To print the message (time), the byte array is converted into a string.

DatagramSocket constructor throws SocketException and receive() method throws IOException.

Executing the above programs

Compile both the programs. To execute on a single system, open two DOS prompts. Treat one DOS prompt as server and execute server program and after at the second DOS prompt run the client program.

Code snippets on UDP protocol are available in Echo Server (UDP) application, the second one on UDP protocol.

Leave a Comment

Your email address will not be published.