LAB ASSIGNMENT - 6
Problem Statement : Write a program using TCP socket for wired network for
File transfer
Code-
Server.java:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("Server started, waiting for connection...");
Socket socket = serverSocket.accept();
System.out.println("Client connected.");
InputStream in = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("received_file.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) > 0) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
socket.close();
serverSocket.close();
System.out.println("File received successfully.");
}
}
Client.java:
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
String filePath = "test.txt"; // Ensure this file exists in the
specified path.
try (Socket socket = new Socket("localhost", 6666);
FileInputStream fis = new FileInputStream(filePath);
OutputStream out = socket.getOutputStream()) {
System.out.println("Connected to server. Sending file...");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
System.out.println("File sent successfully.");
} catch (FileNotFoundException e) {
System.err.println("File not found: " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
test.txt:
Output-