Practical No. 17
Practical No. 17
17
Main program O/P: Java is Easy!!!
Exercise Q.1
import java.net.*; import java.net.*;
import java.util.Scanner; import java.util.Scanner;
O/P:
Q.3
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.Scanner;
public class FileRec {
public static void main(String[] args) throws Exception { public class FileSend {
DatagramSocket socket = new DatagramSocket(9876); public static void main(String[] args) throws Exception {
byte[] recbuf = new byte[1024]; Scanner sc = new Scanner(System.in);
System.out.println("Waiting to receive file..."); System.out.println("Enter the file name to send:");
FileOutputStream fos = new String name = sc.nextLine();
FileOutputStream("ReceivedFile.txt"); File file = new File(name);
while (true) { if (!file.exists()) {
DatagramPacket dp = new DatagramPacket(recbuf, System.out.println("File does not exist.");
recbuf.length); return;
socket.receive(dp); }
String receivedData = new String(packet.getData(), DatagramSocket socket = new DatagramSocket();
0, packet.getLength()); InetAddress ia = InetAddress.getByName("localhost");
if (receivedData.equals("END")) { byte[] sendbuf = new byte[1024];
System.out.println("File transfer completed."); FileInputStream fis = new FileInputStream(file);
break; int readbyte;
} while ((readbyte = fis.read(sendbuf)) != -1) {
fos.write(dp.getData(), 0, dp.getLength()); DatagramPacket dp = new
} DatagramPacket(sendbuf, sendbyte, ia, 92);
fos.close(); socket.send(dp);
socket.close(); }
} String endmsg = "END";
} DatagramPacket ldp = new
DatagramPacket(endmsg.getBytes(), endmsg.length(), ia,
92);
socket.send(ldp);
fis.close();
socket.close();
System.out.println("File sent successfully.");
}
}