javafilesocketsclienttransfer

File transfer Client to Client in JAVA


I need to implement a program to transfer files. I decided to make it using a chat template I've made about 1 month ago so I would have a chat with file transfer option. The transfer should follow the following points:

1- Server only keeps a list of all files provided by connected clients (No file are actually located in the server, only their names)

2- Client "1" requests file "A" then:

if file "A" is located ONLY in client "2", then client "2" should send 100% of the file to client "1"

if file "A" is located in client "2" and client "3" also has file "A", then client "2" should send 50% of the file to client "1" and client "3" should send the other 50%.

(if the file is located in 4 clients it should be 25% each....and so it goes...)

I've already managed to make the server find out which client is requesting the file and which clients have it. But now I'm stuck, I don't know how to make the transfer.

Could someone give me an example of how to do it? or point me through the right direction?

[I'm aware my code has some flaws and I will fix it later, right now I need to make the transfer happen before working on fixes, so please, unless it's related, try to focus on that]

Server:

package tor;

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

public class Server extends Thread {

private String cname;
private Socket client;
public static Vector<PrintStream> clients;
public static Vector<String> clientnames;
public static Vector<String> archives;
public Server(Socket client) {
    this.client = client;

}

public static void main(String[] args) {
    clients = new Vector<PrintStream>();
    clientnames = new Vector<String>();
    archives = new Vector<String>();

    try {

        ServerSocket server = new ServerSocket(2391);
        System.out.println("Server Started!!\n");
        while (true) {
            Socket client = server.accept();
            Server s = new Server(client);
            s.start();
        }

    } catch (IOException e) {
        System.out.println("Server could not start ");

    }

}


@Override
public void run() {

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintStream out = new PrintStream(client.getOutputStream());
        cname = in.readLine();
        System.out.println(cname + " Connected --- SERVER!");

        if (cname == null) {
            System.out.println("Unknown Name");
            return;
        }
        clientnames.add(cname);
        clients.add(out);
        connected(" ********** [", cname, "] Connected! **********");

        String arq;
        int size = in.read();
        System.out.println(size);
        for (int i = 0; i < size; i++) {
            arq = in.readLine();
            archives.add(arq);
        }
        String msg = in.readLine();
        String selected;
        while (true) {
            while (!(msg).equals("/exit") && !(msg).equals("/Exit") && !(msg).equals("/EXIT")) {

                if ((msg).equals("/list") || (msg).equals("/List") || (msg).equals("/list")) {
                    out.println("-------- Archives List --------");
                    for (int i = 0; i < archives.size(); i++) {
                        out.println(i+"- "+archives.get(i));
                    }
                    out.println("-------- ******************* --------");
                    msg = in.readLine();
                } else if (msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))){
                    msg = in.readLine();
                    int gnum = Integer.parseInt(msg);
                    selected=archives.get(gnum);
                    returnAll("[", out, "]: ", "idreq");
                    out.println("1");
                    reqAll(selected);
                    
                    // I BELIVE HERE IS THE RIGHT PLACE TO MAKE DE TRANSFER CODE
                    
                    
                    msg = in.readLine();
                } else {
                    returnAll("[", out, "]: ", msg);
                    msg = in.readLine();
                }
            }
            msg = in.readLine();
            size = Integer.parseInt(msg);
            for (int i = 0; i <= size; i++) {
                arq = in.readLine();
                for(int j=0;j<archives.size();j++) {
                if (archives.get(j).equals(arq)) {
                    archives.remove(j);
                }
                }
            }
            returnAll(" ********** [", out, "] disconnected ", " ********** ");
            clients.remove(out);
            clientnames.remove(cname);
            client.close();
            break;
        }
    } catch (IOException e) {
        System.out.println("A Client disconnected ");
    }

}

// METHOD TO SEND CONNECTION MESSAGE
public void connected(String msg1, String cname, String msg2) throws IOException {
    Enumeration<PrintStream> e = clients.elements();
    while (e.hasMoreElements()) {
        PrintStream message = (PrintStream) e.nextElement();
        message.println(msg1 + cname + msg2);
    }
}

// METHOD TO RETURN MESSAGE TO ALL CLIENTS
public void returnAll(String msg1, PrintStream saida, String ac, String msg2) throws IOException {
    Enumeration<PrintStream> e = clients.elements();
    while (e.hasMoreElements()) {
        PrintStream message = (PrintStream) e.nextElement();
        message.println(msg1 + cname + ac + msg2);
    }
}

public void reqAll(String req) throws IOException {
    Enumeration<PrintStream> e = clients.elements();
    while (e.hasMoreElements()) {
        PrintStream message = (PrintStream) e.nextElement();
        message.println(req);
    }
}


}

Client:

package tor;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;


public class Client extends Thread {
    private Socket con;
    private static boolean done = false;
    static ArrayList<String> localArq = new ArrayList<String>();
    static int c=0;

public Client(Socket s) {
    con = s;
}

public static void main(String[] args) {


    try {
        String ip;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter Server's IP: ");
        ip =s.next();
        Socket con = new Socket(ip, 2391);
        PrintStream out = new PrintStream(con.getOutputStream());
        System.out.println("Connected to Server!");
        System.out.print("Enter your Nickname: ");
        BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
        String cname = scan.readLine();
        out.println(cname);
        String dir="C:\\javator\\"+cname;
        Thread t = new Client(con);
        t.start();
        
        File folder = new File(dir);
        folder.mkdir();
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) {
          if (listOfFiles[i].isFile()) {
            localArq.add(listOfFiles[i].getName());
          }
        }
        int size=localArq.size();
        out.write(size);
        for(int i=0;i<size;i++) {
            out.println(localArq.get(i));
        }
        
        
        String msg;
        while (true) {
            System.out.print("");
            msg = scan.readLine();
            if(msg.equals("/ll")) {
            System.out.println("-------- LOCAL LIST --------");
            for (int i = 0; i < localArq.size(); i++) {
                System.out.println(localArq.get(i));
            }
            System.out.println("-------- ******************* --------");
            msg = scan.readLine();
            }else if(msg.equals("/exit") || (msg.equals("/Exit")) || (msg.equals("/EXIT"))) {
                out.println(msg);
                size=localArq.size();
                out.println(size);
                for(int i=0;i<size;i++) {
                    out.println(localArq.get(i));
                }
                
            }
            else if(msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))) {
                System.out.println("Chose file's number to /get: ");
            c++;
            }
            if (done == true) {
                break;
            }
            out.println(msg);
    }
    } catch (UnknownHostException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

@Override
public void run() {
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String rmsg;
        String req;
        
        while (true) {
            rmsg = in.readLine();
            if (rmsg == null) {
                System.out.println("Connection Terminated");
                break;
            }else if(rmsg.substring(rmsg.length() - 5).equals("idreq")) {
                
                req = in.readLine();
                for(int i=0;i<localArq.size();i++) { //IDENTIFIES WHO OWNS THE REQUESTED FILE
                    if(localArq.get(i).equals(req)) {
                        
                        System.out.println("Owns requested file");
                        Socket requester = new Socket("192.168.3.114", 2007);
                        ObjectOutputStream outputr = new ObjectOutputStream(requester.getOutputStream());
                        ObjectInputStream inputr = new ObjectInputStream(requester.getInputStream());
                        Object mens= inputr.readObject();
                        System.out.println(mens);
                        outputr.writeObject("OWNER FOUND");
                    }
                }
                if(c==1) { //IDENTIFIES WHO WANTS THE FILE
                rmsg = in.readLine();
                c= Integer.parseInt(rmsg);
                System.out.println("file: "+req);
                
                ServerSocket peer = new ServerSocket(2007);
                System.out.println("OPEN FOR CONNECTIONS\n");
                
                    Socket client = peer.accept();
                    System.out.println("Client connected: " + client.getInetAddress().getHostAddress());
                    ObjectOutputStream outputo = new ObjectOutputStream(client.getOutputStream());
                    ObjectInputStream inputo = new ObjectInputStream(client.getInputStream());
                    outputo.flush();
                    outputo.writeObject("Connected to requester");
                    Object mens= inputo.readObject();
                    System.out.println(mens);
                
                }
                
            }
             else {
            System.out.println(rmsg);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    done = true;
}
}

Solution

  • I was able to make a transfer between two clients easily with the information provided and a little research on stackOverflow to understand more about out/inputStreams! This post also helped me a lot: Sending a file with Java Sockets, losing data next step is the shared transfer