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

udp

The document contains Java code for a simple UDP server and client application. The server listens for messages on port 1234, acknowledges received messages, and terminates when it receives the 'exit' command. The client sends messages to the server and displays acknowledgments until it also sends 'exit'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

udp

The document contains Java code for a simple UDP server and client application. The server listens for messages on port 1234, acknowledges received messages, and terminates when it receives the 'exit' command. The client sends messages to the server and displays acknowledgments until it also sends 'exit'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

SERVER:

import java.net.*;
public class es2{
public static void main(String[] args)
{
try
{
DatagramSocket server = new DatagramSocket(1234);
System.out.println("Server is ready!");

byte[] rd = new byte[1024];


DatagramPacket rp = new DatagramPacket(rd,rd.length);

while(true)
{
server.receive(rp);
String msg = new String(rp.getData(),0,rp.getLength());

System.out.println("Msg from client : "+msg);

if(msg.equalsIgnoreCase("exit"))
{
System.out.println("Client gone....");
break;
}

String ack = msg+" ACK";


InetAddress clientAdd = rp.getAddress();
int cport = rp.getPort();
DatagramPacket sd = new DatagramPacket(ack.getBytes(),
ack.length(), clientAdd, cport);
server.send(sd);
}
server.close();
}
catch(Exception e)
{
System.out.print("Errorr!!!!");
}
}
}

Client:

import java.net.*;
import java.util.*;

public class ec2{


public static void main(String[] args) {
try {
DatagramSocket client = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a msg : ");
String msg = sc.nextLine();

InetAddress serveradd = InetAddress.getByName("localhost");


DatagramPacket sd = new DatagramPacket(msg.getBytes(),
msg.length(), serveradd, 1234);
client.send(sd);

if(msg.equalsIgnoreCase("exit"))
{
System.out.print("Bye bye....");
break;
}

byte[] rd = new byte[1024];


DatagramPacket rp = new DatagramPacket(rd, rd.length);
client.receive(rp);

String ack = new String(rp.getData(),0,rp.getLength());


System.out.println("From server : "+ack);

}
client.close();
} catch (Exception e) {
System.out.println("Error.........");
}
}
}

You might also like