Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
29 views

Computer Network Notes

This document contains code for a basic UDP client-server program in Java. The UDP server code creates a datagram socket to listen for incoming packets on port 50000. When a packet is received, it prints the message and sends an acknowledgment back to the client. The UDP client code sends a message to the server on localhost port 50000 containing the username and OS name. It then receives and prints the acknowledgment message sent from the server.

Uploaded by

Ushnish Das
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Computer Network Notes

This document contains code for a basic UDP client-server program in Java. The UDP server code creates a datagram socket to listen for incoming packets on port 50000. When a packet is received, it prints the message and sends an acknowledgment back to the client. The UDP client code sends a message to the server on localhost port 50000 containing the username and OS name. It then receives and prints the acknowledgment message sent from the server.

Uploaded by

Ushnish Das
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

First UDP Program

UDP Server

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer {

public static void main(String[] agrs)throws IOException


{
try
{
DatagramSocket dsocket=new DatagramSocket(50000);
byte[] buffer=new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
while(true){
dsocket.receive(packet);
byte[] bi=packet.getData();
String msg=new String(bi);
System.out.println(msg.trim() + " From port: "+ packet.getPort());
InetAddress address=packet.getAddress();
String msg1="Acknowledged";
DatagramPacket packet1=new DatagramPacket(msg1.getBytes(),msg1.getBytes().length,address,
packet.getPort());
dsocket.send(packet1);
}
} catch(Exception e) {}
}
}

UDP Client

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

public class UDPClient


{
public static void main(String[] args)
{
try {
String s1="USER:"+System.getProperty("user.name")+" OS: "+System.getProperty("os.name");
byte[] msg=s1.getBytes();
InetAddress address=InetAddress.getByName("localhost");
DatagramPacket packet=new DatagramPacket(msg,msg.length,address,50000);
DatagramSocket dsocket=new DatagramSocket();
dsocket.send(packet);
byte[] buffer=new byte[2048];
DatagramPacket packet1=new DatagramPacket(buffer, buffer.length);
dsocket.receive(packet1);
byte[] b=packet1.getData();
String msg1=new String(b);
System.out.println("From Server "+msg1);
dsocket.close();
} catch(Exception e) {}
}
}

You might also like