0% found this document useful (0 votes)
10 views2 pages

Udpfiletransferclient Java

udp tcp

Uploaded by

priya j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views2 pages

Udpfiletransferclient Java

udp tcp

Uploaded by

priya j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Implementation of file transfer using udp

UDPFileTransferClient.java
import java.io.*;
import java.net.*;

public class UDPFileTransferClient {


public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.out.println("Usage: java UDPFileTransferClient <server> <file>");
return;
}

String serverAddress = args[0];


String filePath = args[1];

DatagramSocket clientSocket = new DatagramSocket();


InetAddress serverInetAddress = InetAddress.getByName(serverAddress);
FileInputStream fileInputStream = new FileInputStream("C:\\Users\\Soft\\Music\\cnf\\a.txt");

byte[] sendBuffer = new byte[4096];


int bytesRead;

while ((bytesRead = fileInputStream.read(sendBuffer)) != -1) {


DatagramPacket sendPacket = new DatagramPacket(sendBuffer, bytesRead,
serverInetAddress, 5000);
clientSocket.send(sendPacket);

System.out.println("Packet sent to server");


}

fileInputStream.close();
clientSocket.close();
}
}

UDPFileTransferServer.java
import java.io.*;
import java.net.*;

public class UDPFileTransferServer {


public static void main(String[] args) throws IOException {
DatagramSocket serverSocket = new DatagramSocket(5000);
System.out.println("Server is listening on port 5000");

byte[] receiveBuffer = new byte[4096];


FileOutputStream fileOutputStream = new FileOutputStream("received_file");

while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
serverSocket.receive(receivePacket);

byte[] data = receivePacket.getData();


int bytesRead = receivePacket.getLength();

fileOutputStream.write(data, 0, bytesRead);

System.out.println("Packet received and written to file");

}
}

You might also like