File transfer Client to Client in JAVA











up vote
1
down vote

favorite












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 i should be 25% each....and so it goes...)



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



Could someone give me an exemple 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 CONNECTIONSn");

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;
}
}









share|improve this question
























  • What transfer do you not know how to make? The file transfer proceeds like every other socket connection, you must have one peer act as the client and initiate a connection to the other peer which must act as the server, listening on a port that the client knows and waiting for the connection.
    – James K Polk
    Nov 12 at 22:40










  • hmm....the client who owns the file should open a seversocket so the one who wants the file can connect to it just like the server then? Can a client connect to more than one serversocket at a time?
    – Bruno Lira
    Nov 12 at 23:00










  • Of course, a client can (and does) have numerous connections open at a time.
    – James K Polk
    Nov 12 at 23:47






  • 1




    @JamesKPolk you sir helped me a lot with this useful information! I was able to transfer from one client to another easily! Next estep, shared transfer and then I can fix and organize my code!
    – Bruno Lira
    Nov 13 at 20:15















up vote
1
down vote

favorite












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 i should be 25% each....and so it goes...)



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



Could someone give me an exemple 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 CONNECTIONSn");

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;
}
}









share|improve this question
























  • What transfer do you not know how to make? The file transfer proceeds like every other socket connection, you must have one peer act as the client and initiate a connection to the other peer which must act as the server, listening on a port that the client knows and waiting for the connection.
    – James K Polk
    Nov 12 at 22:40










  • hmm....the client who owns the file should open a seversocket so the one who wants the file can connect to it just like the server then? Can a client connect to more than one serversocket at a time?
    – Bruno Lira
    Nov 12 at 23:00










  • Of course, a client can (and does) have numerous connections open at a time.
    – James K Polk
    Nov 12 at 23:47






  • 1




    @JamesKPolk you sir helped me a lot with this useful information! I was able to transfer from one client to another easily! Next estep, shared transfer and then I can fix and organize my code!
    – Bruno Lira
    Nov 13 at 20:15













up vote
1
down vote

favorite









up vote
1
down vote

favorite











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 i should be 25% each....and so it goes...)



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



Could someone give me an exemple 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 CONNECTIONSn");

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;
}
}









share|improve this question















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 i should be 25% each....and so it goes...)



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



Could someone give me an exemple 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 CONNECTIONSn");

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;
}
}






java file sockets client transfer






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 at 17:20

























asked Nov 12 at 20:33









Bruno Lira

112




112












  • What transfer do you not know how to make? The file transfer proceeds like every other socket connection, you must have one peer act as the client and initiate a connection to the other peer which must act as the server, listening on a port that the client knows and waiting for the connection.
    – James K Polk
    Nov 12 at 22:40










  • hmm....the client who owns the file should open a seversocket so the one who wants the file can connect to it just like the server then? Can a client connect to more than one serversocket at a time?
    – Bruno Lira
    Nov 12 at 23:00










  • Of course, a client can (and does) have numerous connections open at a time.
    – James K Polk
    Nov 12 at 23:47






  • 1




    @JamesKPolk you sir helped me a lot with this useful information! I was able to transfer from one client to another easily! Next estep, shared transfer and then I can fix and organize my code!
    – Bruno Lira
    Nov 13 at 20:15


















  • What transfer do you not know how to make? The file transfer proceeds like every other socket connection, you must have one peer act as the client and initiate a connection to the other peer which must act as the server, listening on a port that the client knows and waiting for the connection.
    – James K Polk
    Nov 12 at 22:40










  • hmm....the client who owns the file should open a seversocket so the one who wants the file can connect to it just like the server then? Can a client connect to more than one serversocket at a time?
    – Bruno Lira
    Nov 12 at 23:00










  • Of course, a client can (and does) have numerous connections open at a time.
    – James K Polk
    Nov 12 at 23:47






  • 1




    @JamesKPolk you sir helped me a lot with this useful information! I was able to transfer from one client to another easily! Next estep, shared transfer and then I can fix and organize my code!
    – Bruno Lira
    Nov 13 at 20:15
















What transfer do you not know how to make? The file transfer proceeds like every other socket connection, you must have one peer act as the client and initiate a connection to the other peer which must act as the server, listening on a port that the client knows and waiting for the connection.
– James K Polk
Nov 12 at 22:40




What transfer do you not know how to make? The file transfer proceeds like every other socket connection, you must have one peer act as the client and initiate a connection to the other peer which must act as the server, listening on a port that the client knows and waiting for the connection.
– James K Polk
Nov 12 at 22:40












hmm....the client who owns the file should open a seversocket so the one who wants the file can connect to it just like the server then? Can a client connect to more than one serversocket at a time?
– Bruno Lira
Nov 12 at 23:00




hmm....the client who owns the file should open a seversocket so the one who wants the file can connect to it just like the server then? Can a client connect to more than one serversocket at a time?
– Bruno Lira
Nov 12 at 23:00












Of course, a client can (and does) have numerous connections open at a time.
– James K Polk
Nov 12 at 23:47




Of course, a client can (and does) have numerous connections open at a time.
– James K Polk
Nov 12 at 23:47




1




1




@JamesKPolk you sir helped me a lot with this useful information! I was able to transfer from one client to another easily! Next estep, shared transfer and then I can fix and organize my code!
– Bruno Lira
Nov 13 at 20:15




@JamesKPolk you sir helped me a lot with this useful information! I was able to transfer from one client to another easily! Next estep, shared transfer and then I can fix and organize my code!
– Bruno Lira
Nov 13 at 20:15












1 Answer
1






active

oldest

votes

















up vote
0
down vote













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






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269682%2ffile-transfer-client-to-client-in-java%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    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






    share|improve this answer

























      up vote
      0
      down vote













      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






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        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






        share|improve this answer












        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







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 at 20:18









        Bruno Lira

        112




        112






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269682%2ffile-transfer-client-to-client-in-java%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            鏡平學校

            ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

            Guess what letter conforming each word