Java TCP File transfer Authentication

Code is written in java. I've got two classes 'server' and 'client'. Client requests a file from server and server sends it to the client. I would like a user authentication when client requests a file from the server. so client can enter username/pw

How should i go about doing this?
import java.net.*;
import java.io.*;

public class FileClient {

    final static String host = "127.0.0.1";
    final static int port = 13267;

    public static void main(String[] args) throws IOException {

        int i = 0;
        /*
         * still not simultanous run need to test in different machine
         */
       // while (i < 2) {

            MyClient client = new MyClient(host, port);
          //  i++;
        //}
    }
}

class MyClient {

    private Socket clientSocket;

    public MyClient(String host, int port) throws IOException {
        clientSocket = new Socket(host, port);
        requestFile();

    }

    public void requestFile() throws IOException {

        System.out.println("Connecting...");
        /*
         * NEED TO REMODULE THE REQUEST FILE TO FILE SERVER
         * POSSIBILTY TO CHANGE THE FILE SIZE HARDCODED TO SIZE OF FILE IN SERVER
         * AUTHENTICATION PROCESSES
         */
		int filesize = 6022386; // filesize temporary hardcoded
		long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;
        //string typed by the user and sent to server
		String sentence;

			//inFromServer provides user to input into the socket
        BufferedReader inFromUser =
        new BufferedReader(new InputStreamReader(System.in));

        //outToServer outputs to the server
        DataOutputStream outToServer =
            new DataOutputStream(clientSocket.getOutputStream());

		//places a line typed by user into the string sentence
		sentence = inFromUser.readLine();

		//sends the string sentence into outtoserver.
		outToServer.writeBytes(sentence +  '\n');

        // receive file
        byte[] mybytearray = new byte[filesize];
        InputStream myInputStream = clientSocket.getInputStream();
        FileOutputStream fileOutStream = new FileOutputStream("copy" + sentence);
        BufferedOutputStream bufferOutStream = new BufferedOutputStream(fileOutStream);

        bytesRead = myInputStream.read(mybytearray, 0, mybytearray.length);
        current = bytesRead;


        do {

            bytesRead =
                    myInputStream.read(mybytearray, current, (mybytearray.length - current));
            if (bytesRead >= 0) {
                current += bytesRead;
            }
        } while (bytesRead > -1);


        bufferOutStream.write(mybytearray, 0, current);
        bufferOutStream.flush();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
		bufferOutStream.close();
        clientSocket.close();
    }
}


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

public class FileServer {

    public static void main(String[] args) throws IOException {
        // create socket
        ServerSocket servsock = new ServerSocket(13267);
        while (true) {
            System.out.println("Waiting...");

            Socket sock = servsock.accept();
            System.out.println("Accepted connection : " + sock);

            // sendfile
            if (sock != null) {

                Client client = new Client(sock);
                client.start();

            }

        }
    }
}



class Client extends Thread {

    private Socket connectionSocket;
    private File myFile;
    private FileInputStream fileInputStream;
    private BufferedInputStream bufferInputStream;
    private byte[] mybytearray;
   String clientSentence;


    public Client(Socket c) throws IOException {
        connectionSocket = c;
    }


    @Override
    public void run() {
		try {
			  BufferedReader inFromClient =
            new BufferedReader(new InputStreamReader(connectionSocket.getInputStream
()));

	//used to send file to client
		OutputStream outPutStream =
            new DataOutputStream(connectionSocket.getOutputStream());

		//use to read file name from client
        clientSentence = inFromClient.readLine();

            myFile = new File(clientSentence);
            mybytearray = new byte[(int) myFile.length()];
            fileInputStream = new FileInputStream(myFile);
            bufferInputStream = new BufferedInputStream(fileInputStream);
            bufferInputStream.read(mybytearray, 0, mybytearray.length);
            //outPutStream = connectionSocket.getOutputStream();
            System.out.println("Sending...");
            outPutStream.write(mybytearray, 0, mybytearray.length);
            outPutStream.flush();
            System.out.println("File sent successfully");
            connectionSocket.close();
			System.out.println("Waiting...");
        } catch (IOException e) {
            System.out.println("Error: " + e);
        }
    }
}

Open in new window

yinnykAsked:
Who is Participating?
 
Amitkumar PConnect With a Mentor Sr. ConsultantCommented:
yinnyk,

Agreed with CEHJ.
What you can do here is that you need to authenticate the user first then request for file in case of a valid user. But in this case your client will have to make two calls (authenticate and request)  to server.

Other thing you can do is that user (client) will request for a file by passing the user credentials. Server will authenticate the client, if it is valid, a file will be sent to client otherwise an error code will be sent to client indicating invalid user/password.
0
 
CEHJCommented:
It's pretty straightforward - you get the server to send an 'authenticate' instruction to the client and then get the client to return the username and password
0
 
CEHJCommented:
yinnyk, can you tell me why you ignored my answer?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.