0% found this document useful (0 votes)
9 views2 pages

UDP

The document provides a Java program implementation for a UDP server and client. The server listens for incoming messages on port 9876 and prints them to the console, while the client sends a 'Hello, UDP Server!' message to the server. Both server and client handle exceptions and ensure proper socket closure after execution.

Uploaded by

basiwa4442
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

UDP

The document provides a Java program implementation for a UDP server and client. The server listens for incoming messages on port 9876 and prints them to the console, while the client sends a 'Hello, UDP Server!' message to the server. Both server and client handle exceptions and ensure proper socket closure after execution.

Uploaded by

basiwa4442
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

RITAM DATTA

11500122089
1. WRITE A JAVA PROGRAM TO IMPLIMENT UDP SERVER CLIENT PROBLEM.

CODE:
SERVER:
// UDPServer.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServer {


public static void main(String[] args) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];

while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received: " + message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}
}

CLIENT:
// UDPClient.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {


public static void main(String[] args) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost");
String message = "Hello, UDP Server!";
byte[] sendData = message.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, 9876);


socket.send(sendPacket);
System.out.println("Message sent to server: " + message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}
}
OUTPUT:
SERVER:
CLIENT:

You might also like