Implement TCP Server for transferring files using Socket and ServerSocket. - Tips N TRIKS

Sunday 25 June 2017

Implement TCP Server for transferring files using Socket and ServerSocket.

Source Code:


Client side
import java.io.*;
import java.net.*;
class Client_TcpFile
{
                  public static void main(String[] args) throws IOException
                  {
                              int fsize=2000;
                              int n;
                              Socket soc=new Socket("localhost",2000);
                              byte[] barray=new byte[fsize];
                              InputStream in=soc.getInputStream();
                              FileOutputStream fout=new FileOutputStream("D:/CP-6/Adv Java/LAB/Lab 1/File_check.docx");


                              BufferedOutputStream bout=new BufferedOutputStream(fout);
                              n=in.read(barray,0,barray.length);
                              do
                              {
                                          n = in.read(barray, 0, barray.length);
                                          if(n >= 0)
                                                      n++;
                              }while(n > -1);
                              bout.write(barray, 0 , barray.length);
                              bout.flush();
                              bout.close();
                              soc.close();
                  }
}
Server side
import java.io.*;
import java.net.*;
public class Server_TcpFile
{
      public static void main (String [] args ) throws IOException
      {
                  ServerSocket ssoc = new ServerSocket(2000);
                  Socket soc = ssoc.accept();
                  System.out.println("Connection established: " + soc);
                  File f = new File ("D:/CP-6/Adv Java/LAB/Lab 1/File_check.docx");
                  byte [] barray = new byte [(int)f.length()];
                  FileInputStream fin = new FileInputStream(f);
                  BufferedInputStream bin = new BufferedInputStream(fin);
                  bin.read(barray,0,barray.length);
                  OutputStream out = soc.getOutputStream();
                  System.out.println("Sending Files...");
                  out.write(barray,0,barray.length);
                  out.flush();
                  soc.close();
                  System.out.println("File transfer completed");
      }

}

Output:


No comments:

Post a Comment