[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Java TCP File transfer Authentication

Posted on 2011-05-09
3
Medium Priority
?
681 Views
Last Modified: 2012-05-11
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

0
Comment
Question by:yinnyk
  • 2
3 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 35718697
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
 
LVL 21

Accepted Solution

by:
Amitkumar P earned 2000 total points
ID: 35718743
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 35744750
yinnyk, can you tell me why you ignored my answer?
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: rfc1180
The Maximum Segment size (MSS) is an important consideration when troubleshooting connectivity via the Internet/Intranet. As the packets are routed via the Internet/Intranet, the packets must traverse through multiple routers in the path between two…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month18 days, 17 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question