Sitemap
Mm Aathik

Mm Aathik

1 min readSep 29, 2024

--

UDP client-server connection in java

Necessary classes:

import java.net.DatagramPacket;
import java.net.DatagramSocket;

Create a socket to listen on a port

DatagramSocket udpServerSocket = new DatagramSocket(8085);

Create a byte array buffer to hold incoming data

byte[] incomingBuffer = new byte[1024]

Create a DatagramPacket to receive incoming packets using the allocated array buffer

DatagramPacket incomingPacket = 
new DatagramPacket(incomingBuffer,
incomingBuffer.length)

Receive the packet

udpServerSocket.receive(incomingPacket);

Convert received packet’s data into string

String gotMsg = new String(
incomingPacket.getData(),0,
incomingPacket.getLength()
);

Print the message

System.out.println("received msg: "+gotMsg);

Create a response message

String res = "Hello Mr. AK!";

Convert response to byte array buffer

byte[] resBuffer = res.getBytes();

Create datagram to send response - get ip address and port from received data.

DatagramPacket resPacket = new DatagramPacket
( resBuffer, resBuffer.length,
incomingPacket.getAddress(),
incomingPacket.getPort()
);

Send the response packet using udp socket server

udpServerSocket.send(resPacket);

Client Side

Actually no client -server; Just 2 devices; The conversatin-starter is treated/claimed as client for naming conventions.

Get Mm Aathik’s stories in your inbox

Join Medium for free to get updates from this writer.

So all codes are same except one thing which is the socket creation part.

No need to listen to any port while creating the socket.

Just need to use port and address while creating packet.

--

--