0% found this document useful (0 votes)
43 views3 pages

TCP File Transfer in Java

ADVANCE JAVA PRACTICLE

Uploaded by

Devisha Gajjar
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)
43 views3 pages

TCP File Transfer in Java

ADVANCE JAVA PRACTICLE

Uploaded by

Devisha Gajjar
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

ADAVANCE JAVA 210470107019

Practical : 2

1) Implement TCP Server for transferring files using Socket and Server
Socket.

TCP-Server
import java.io.*;
import java.net.*;

public class tcp_server{


public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(888);
System.out.println();
System.out.print("Server is waiting for connections…");
Socket s = ss.accept();
System.out.println("Connection is Established.....");

InputStream inputStream = s.getInputStream();


BufferedReader inputReader = new BufferedReader(new
InputStreamReader(inputStream));

String fileName = inputReader.readLine();


System.out.println("\nReceiving file: " + fileName);
System.out.println("File received successfully.....");

BufferedReader fileReader = new BufferedReader(new


FileReader(fileName));

String line;
System.out.print("\nFile Content : ");
while ((line = fileReader.readLine())!= null) {
System.out.println(line);
}
fileReader.close();

// writing data in received file


String addData = "Appended data: Hello World!!";
FileWriter fileWriter = new FileWriter(fileName, true);
fileWriter.write("\n" + addData);
fileWriter.close();
5
ADAVANCE JAVA 210470107019

System.out.println("String appended to file...\n");

s.close();
ss.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}

TCP-Client

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

public class tcp_client {


public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 888);
System.out.println("\nConnected to server.");

OutputStream outputStream = s.getOutputStream();


PrintWriter writer = new PrintWriter(outputStream,
true);

String fileName = "sample.txt";


writer.println(fileName);
System.out.println("File sent successfully....\n");

s.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

6
ADAVANCE JAVA 210470107019

Output:

You might also like