0% found this document useful (0 votes)
8 views

Network Programming Section 8

Uploaded by

basma
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)
8 views

Network Programming Section 8

Uploaded by

basma
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/ 4

Prepared by: Eng/ Basma Elshoky

Section 8: User Datagram Protocol (UDP) part II

Example of a simple UDP client and server implemented in Java:


UDP Client Example:
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
final String serverHost = "localhost";
final int serverPort = 12345;
try {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName(serverHost);
byte[] sendData = "Hello, UDP Server!".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, serverAddress, serverPort);
clientSocket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String receivedMessage = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("From Server: " + receivedMessage);
Prepared by: Eng/ Basma Elshoky

clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

UDP Server Example:


import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String[] args) {
final int serverPort = 12345;
try {
DatagramSocket serverSocket = new DatagramSocket(serverPort);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while (true) {
serverSocket.receive(receivePacket);
String clientMessage = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("From Client: " + clientMessage);
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
Prepared by: Eng/ Basma Elshoky

byte[] sendData = "Hello, UDP Client!".getBytes();


DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Instructions for Running:


Run UDPServer first.
Then, run UDPClient.
You should see messages exchanged between the client and server printed on the
console.
These examples demonstrate a basic UDP client-server interaction in Java. The
client sends a message to the server, and the server responds with another message.
Prepared by: Eng/ Basma Elshoky

You might also like