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

Implementation of File Transfer Using TCP Filetransferclient .Java

cnf lab

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

Implementation of File Transfer Using TCP Filetransferclient .Java

cnf lab

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 TCP

FileTransferClient .java

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

public class FileTransferClient {


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

String serverAddress = args[0];


String filePath = args[1];

Socket socket = new Socket(serverAddress, 5000);


FileInputStream fileInputStream = new FileInputStream(filePath);
OutputStream outputStream = socket.getOutputStream();

byte[] buffer = new byte[4096];


int bytesRead;

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


outputStream.write(buffer, 0, bytesRead);
}

System.out.println("File sent successfully");

fileInputStream.close();
socket.close();
}
}

FileTransferServer.java:

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

public class FileTransferServer {


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

while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected");

InputStream inputStream = socket.getInputStream();


FileOutputStream fileOutputStream = new FileOutputStream("received_file");

byte[] buffer = new byte[4096];


int bytesRead;

while ((bytesRead = inputStream.read(buffer)) != -1) {


fileOutputStream.write(buffer, 0, bytesRead);
}

System.out.println("File received successfully");

fileOutputStream.close();
socket.close();
}
}
}

You might also like