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

Dcpractical 4

The document describes a UDP server and client program written in Java. The UDP server creates a datagram socket to listen for incoming packets on port 6789, receives packets into a buffer, and immediately sends the buffer contents back as a response. The UDP client sends a datagram packet to the server containing a message and prints the server's response. Both close the socket when done.

Uploaded by

swadeepti
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Dcpractical 4

The document describes a UDP server and client program written in Java. The UDP server creates a datagram socket to listen for incoming packets on port 6789, receives packets into a buffer, and immediately sends the buffer contents back as a response. The UDP client sends a datagram packet to the server containing a message and prints the server's response. Both close the socket when done.

Uploaded by

swadeepti
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 3

Practical 4

UDP Server

import java.net.*;
import java.io.*;
public class UDPServer
{
public static void main(String args[])
{
DatagramSocket aSocket = null;
try
{
aSocket = new DatagramSocket(6789);
byte[] buffer = new byte[1000];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer,
buffer.length);
aSocket.receive(request);
DatagramPacket reply = new
DatagramPacket(request.getData(),
request.getLength(), request.getAddress(),
request.getPort());
aSocket.send(reply);
}
}catch (SocketException e){System.out.println("Socket: "
+e.getMessage());}
catch (IOException e) {System.out.println("IO: "
+e.getMessage());}
finally {if(aSocket != null) aSocket.close();}
}
}
UDP Client

import java.net.*;
import java.io.*;
public class UDPClient{
public static void main(String args[]){
// args give message contents and server hostname
DatagramSocket aSocket = null;
try {
aSocket = new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = 6789;
DatagramPacket request = new DatagramPacket(m,
args[0].length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer,
buffer.length);
aSocket.receive(reply);
System.out.println("Reply: " + new String(reply.getData()));
}catch (SocketException e){System.out.println("Socket: " +
e.getMessage());}
catch (IOException e){System.out.println("IO: " + e.getMessage());}
finally {if(aSocket != null) aSocket.close();}
}
}
OUTPUT:

UDPServer

UDPClient

You might also like