Tuesday, October 10, 2017

FTP server client simulation using socket program

This JAVA socket program will download webpage (HTML file) from server to client. Downloaded file will be opened into web browser.

SERVER side program

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

public class FTPServer {
  public static void main(String[] args) throws IOException {
    //server will start at port number 12345.
    ServerSocket servsock = new ServerSocket(12345);

    //server will send index1.htm file to client.
    File myFile = new File("D:\\index1.htm");
    System.out.println("Waiting for Client Request...");
    while (true) {
      Socket sock = servsock.accept();
      byte[] mybytearray = new byte[(int) myFile.length()];
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
      bis.read(mybytearray, 0, mybytearray.length);
      OutputStream os = sock.getOutputStream();
      os.write(mybytearray, 0, mybytearray.length);
      os.flush();
      sock.close();
    }
  }
}

SERVER side Output:

Waiting for Client Request...



CLIENT side program

import java.awt.Desktop;
import java.io.*;
import java.net.*;

public class FTPClient {
  public static void main(String[] argv) throws Exception {

    //socket will be created local IP: 127.0.0.1 and port 12345.
    Socket sock = new Socket("127.0.0.1", 12345);
    byte[] mybytearray = new byte[1024];
   
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream("D:\\index2.htm");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
   
    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
    bos.write(mybytearray, 0, bytesRead);
   
    System.out.println("File downloaded...");
   
    Following code will open index2.htm file in browser.

    String url="D:\\index2.htm";
    File htmlFile=new File(url);
    Desktop.getDesktop().browse(htmlFile.toURI());

    bos.close();
    sock.close();
  }
}

CLIENT side output:

File downloaded...
BUILD SUCCESSFUL (total time: 1 second)



No comments:

Post a Comment