Current results (Server
on the left) (Client
on the right):
https://www.dropbox.com/s/tpgiu9kvn95f5z2/asc.png?dl=0
Notice: On the bottom of the left window (Server
), the message that says "Sending hello.txt(19 bytes) is not accurate because the bottom window shows the file hello.txt
but it contains zero bytes if you look to the right of it. The message 849392 on the right window (Client)
is the last message that is printed out by the system.out.println
before the inputStream.read function starts blocking/stalling forever.
The line that is causing the block is:
bytesRead = inputStream.read(byteArray,0,byteArray.length);
The following line would have been printed out if the above line did not block/pause/stall:
System.out.println("File " + fileLocation + " downloaded ( size: " + current + " bytes read)");
My question is: How should I go about sending the file size, the file name, and the file path/location to this client so that it will stop blocking/stalling forever?
How it is being sent:
FileInputStream fis = null;
OutputStream os = null;
File myFile = new File(filename);
byte [] mybytearray = new byte [(int)myFile.length()];
fileSize2 = mybytearray.length;
sendFileSize(servSocket, fileSize2);
try
{
fis = new FileInputStream(myFile);
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + myFile.getPath() + " was not found.\n");
System.out.println("Please try again.");
}
os = servSocket.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)");
How it is being received:
public static void receiveFile(int portNo, String fileLocation, Socket socket, int size) throws IOException
{
int bytesRead=0;
int current = 0;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try
{
byte [] byteArray = new byte [size];
System.out.println("26");
InputStream inputStream = socket.getInputStream();
System.out.println("3453");
fileOutputStream = new FileOutputStream(fileLocation);
System.out.println("43252");
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
System.out.println("849392");
bytesRead = inputStream.read(byteArray,0,byteArray.length);
current = bytesRead;
do
{
bytesRead =inputStream.read(byteArray, current, (byteArray.length-current));
if(bytesRead >= 0) current += bytesRead;
}
while(bytesRead > -1);
bufferedOutputStream.write(byteArray, 0 , current);
bufferedOutputStream.flush();
System.out.println("File " + fileLocation + " downloaded ( size: " + current + " bytes read)");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
Note: If you already know the answer by this point, SKIP reading the rest of the code and scroll down to post an answer thanks.
Full code of Client.java
:
import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.file.*;
import static java.nio.charset.StandardCharsets.*;
public class Client implements Runnable
{
public boolean isConnected = true;
int ConnectOnce = 0;
public String[] clientArgs;
public static Socket socket;
public Socket fileSocket;
public boolean keepRunning = true;
public String option = "";
public int differentPort;
public int ConnectOnce1 = 0;
public int normalPort = 0;
public Client(String[] args) throws IOException
{
this.clientArgs = args;
if(ConnectOnce == 0)
{
try
{
differentPort = Integer.valueOf(clientArgs[1]);
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
String port_number1= clientArgs[3];
normalPort = Integer.valueOf(port_number1);
socket = new Socket(address, normalPort);
ConnectOnce = 4;
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
public String[] clientRun2(String[] args)
{
clientArgs = args;
clientArgs = Arrays.copyOf(args, args.length);
clientSend.start();
return clientArgs;
}
Thread clientSend = new Thread()
{
public void run()
{
OutputOptions();
while(isConnected)
{
try
{
ClientRecieve clientThread = new ClientRecieve(socket);
clientThread.start();
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String line2 = "";
line2= input2.readLine();
if(line2.equals("m") || line2.equals("M"))
{
ClientSend();
}
else if(line2.equals("f") || line2.equals("F"))
{
SendFileName();
}
else if(line2.equals("x") || line2.equals("X"))
{
System.exit(0);
}
else if(!line2.equals("x") && !line2.equals("X") && !line2.equals("m")
&& !line2.equals("M") && !line2.equals("f") && !line2.equals("F"))
{
System.out.println("(invalid choice)");
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
}
}
};
public void ClientSend()
{
try
{
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String newmessage = "";
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println("Enter your message: ");
line= input.readLine();
newmessage += line + " ";
String sendMessage = newmessage;
bw.write(sendMessage + " " + differentPort + "\n");
bw.newLine();
bw.flush();
StandardInput();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
public void SendFileName() throws FileNotFoundException
{
try
{
String fileNameAgain = "";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String newmessage = "";
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println("Which file do you want?");
line= input.readLine();
fileNameAgain = line;
newmessage += line + " ";
String filename = newmessage;
bw.write("filenameistotheright->` " + filename);
bw.newLine();
bw.flush();
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
s = s + "/" + fileNameAgain;
int size = 0;
size = recieveSizeAndPath(socket);
receiveFile(normalPort, s, socket, size);
StandardInput();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public int recieveSizeAndPath(Socket socket)
{
int size = 0;
try
{
BufferedReader readfromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fromServer = readfromServer.readLine();
if(fromServer!=null && !fromServer.isEmpty())
{
if(fromServer.contains("size"))
{
String string = fromServer;
String[] parts = string.split(":");
String part1 = parts[0];
String part2 = parts[1];
System.out.println("Size of file is: " + part2);
size = Integer.valueOf(part2);
return size;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
return size;
}
public static void receiveFile(int portNo, String fileLocation, Socket socket, int size) throws IOException
{
int bytesRead=0;
int current = 0;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try
{
byte [] byteArray = new byte [size];
System.out.println("26");
InputStream inputStream = socket.getInputStream();
System.out.println("3453");
fileOutputStream = new FileOutputStream(fileLocation);
System.out.println("43252");
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
System.out.println("849392");
bytesRead = inputStream.read(byteArray,0,byteArray.length);
current = bytesRead;
do
{
bytesRead =inputStream.read(byteArray, current, (byteArray.length-current));
if(bytesRead >= 0) current += bytesRead;
}
while(bytesRead > -1);
bufferedOutputStream.write(byteArray, 0 , current);
bufferedOutputStream.flush();
System.out.println("File " + fileLocation + " downloaded ( size: " + current + " bytes read)");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
Thread ClientRead = new Thread();
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
@Override
public void run()
{
}
public void StandardInput()
{
OutputOptions();
while(true)
{
String option = "";
String newmessage = "";
try
{
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String line2 = "";
line2= input2.readLine();
if(line2.equals("m") || line2.equals("M"))
{
ClientSend();
}
if(line2.equals("f") || line2.equals("F"))
{
SendFileName();
}
if(line2.equals("x") || line2.equals("X"))
{
System.exit(0);
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
finally
{
}
}
}
}
Full code of Server.java
:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class Server
{
private String[] serverArgs;
public Socket socket;
public Socket fileSocket;
public boolean keepRunning = true;
public int ConnectOnce = 0;
public String option = "";
public boolean isConnected = false;
public Server(String[] args) throws IOException
{
this.serverArgs = args;
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
isConnected = true;
}
}
public String[] serverRun2(String[] args) throws IOException
{
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
serverSend.start();
return serverArgs;
}
Thread serverSend = new Thread()
{
public void run()
{
OutputOptions();
while(isConnected)
{
try
{
ServerRecieve serverThread = new ServerRecieve(socket);
serverThread.start();
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
option = input2.readLine();
if(option.equals("m") || option.equals("M"))
{
StandardOutput();
}
else if(option.equals("f") || option.equals("F"))
{
SendFileName();
}
else if(option.equals("x") || option.equals("X"))
{
System.exit(0);
}
else if(!option.equals("x") && !option.equals("X") && !option.equals("m")
&& !option.equals("M") && !option.equals("f") && !option.equals("F"))
{
System.out.println("(invalid choice)");
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
}
}
};
public void StandardOutput()
{
try
{
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String newmessage = "";
try
{
System.out.println("Enter your message: ");
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input2.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.newLine();
bw.flush();
StandardInput();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
public void SendFileName() throws FileNotFoundException
{
try
{
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String newmessage = "";
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println("What file do you want?");
line= input.readLine();
newmessage += line + " ";
String filename = newmessage;
bw.write("filenameistotheright->` " + filename);
bw.newLine();
bw.flush();
int bytesRead = 0;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int size = (int)filename.length();
byte [] mybytearray = new byte[size];
InputStream is = socket.getInputStream();
fos = new FileOutputStream(filename);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
if(bytesRead > -1)
{
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0)
{
current += bytesRead;
}
}
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + filename + " downloaded (" + current + " bytes read)");
StandardInput();
}
catch (IOException e)
{
e.printStackTrace();
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
public void StandardInput()
{
OutputOptions();
while(true)
{
try
{
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String option = "";
option= input2.readLine();
if(option.equals("m") || option.equals("M"))
{
StandardOutput();
}
if(option.equals("f") || option.equals("F"))
{
SendFileName();
}
if(option.equals("x") || option.equals("X"))
{
System.exit(0);
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
}
}
}
}
Full code of ClientRecieve.java
:
import java.net.*;
import java.io.*;
public class ClientRecieve extends Thread
{
int filePortNumber = 0;
Socket servSocket;
Socket fileSocket;
boolean m_bRunThread = true;
boolean ServerOn = true;
int once = 0;
String fileNameGlobal = "";
public ClientRecieve(Socket s) throws FileNotFoundException
{
super();
this.servSocket = s;
}
public void run()
{
while(true)
{
try
{
BufferedReader readfromServer = new BufferedReader(new InputStreamReader(servSocket.getInputStream()));
String fromServer = readfromServer.readLine();
if(fromServer!=null && !fromServer.isEmpty())
{
if(fromServer.contains("size"))
{
System.out.println(fromServer);
}
String a = fromServer;
int i;
for(i = 0; i < a.length(); i++)
{
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
{
break;
}
}
String alphaPart = a.substring(0, i);
System.out.println(alphaPart);
}
if(fromServer.equals(null))
{
System.exit(0);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
public int strToInt( String str )
{
int i = 0;
int num = 0;
boolean isNeg = false;
if (str.charAt(0) == '-')
{
isNeg = true;
i = 1;
}
while( i < str.length())
{
num *= 10;
num += str.charAt(i++) - '0';
}
if (isNeg)
{
num = -num;
}
return num;
}
}
Full code of ServerRecieve.java
:
import java.net.*;
import java.io.*;
public class ServerRecieve extends Thread
{
int fileSize2 = 0;
int filePortNumber = 0;
Socket servSocket;
Socket fileSocket;
boolean m_bRunThread = true;
boolean ServerOn = true;
int gotPortNumber = 0;
int once = 0;
String fileNameGlobal = "";
int fileSizeGlobal = 0;
public ServerRecieve(Socket s) throws FileNotFoundException
{
super();
this.servSocket = s;
}
public void run()
{
while(true)
{
try
{
BufferedReader readFromClient = new BufferedReader(new InputStreamReader(servSocket.getInputStream()));
String fromClient = readFromClient.readLine();
if(fromClient.contains("size"))
{
System.out.println(fromClient);
}
if(fromClient.contains("filenameistotheright->` ") == true)
{
String[] parts = fromClient.split(" ");
String filename = parts[1];
System.out.println("Requested filename is: " + filename);
if(filename == "i")
{
System.out.println("Please request the file again");
}
fileNameGlobal = filename;
fileSizeGlobal = filename.length();
if(fileSizeGlobal > 0 && !fileNameGlobal.isEmpty())
{
//send file size and location to client here?
//socket is already being used to read...
}
if(once == 0 && filename != "i")
{
String[] parts12 = fromClient.split("`");
String filename31 = parts12[1];
String a = fromClient;
int i;
for(i = 0; i < a.length(); i++)
{
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
{
break;
}
}
String numberPart = a.substring(i);
if(gotPortNumber == 0 && filename != "i")
{
System.out.println("File transfer port found: " + numberPart + "\n");
gotPortNumber = 3;
filePortNumber = Integer.parseInt(numberPart);
int p = 0;
p = strToInt(numberPart);
if(filename31 != null && !filename31.isEmpty())
{
ServerFile getServerFile = new ServerFile(servSocket, p, filename31);
getServerFile.start();
gotPortNumber = 3;
}
gotPortNumber = 3;
}
once = 4;
}
once = 4;
FileInputStream fis = null;
OutputStream os = null;
File myFile = new File(filename);
byte [] mybytearray = new byte [(int)myFile.length()];
fileSize2 = mybytearray.length;
sendFileSize(servSocket, fileSize2);
try
{
fis = new FileInputStream(myFile);
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + myFile.getPath() + " was not found.\n");
System.out.println("Please try again.");
}
os = servSocket.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)");
}
else
{
String a = fromClient;
int i;
for(i = 0; i < a.length(); i++)
{
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
{
break;
}
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);
System.out.println(alphaPart);
if(gotPortNumber == 0 )
{
gotPortNumber = 3;
filePortNumber = Integer.parseInt(numberPart);
int p = 0;
p = strToInt(numberPart);
}
gotPortNumber = 3;
if(fromClient.equals(null))
{
System.exit(0);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
public void sendFileSize(Socket socket4, int fileSize)
{
try
{
OutputStream os = socket4.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("File size is:" + fileSize);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
public int strToInt( String str )
{
int i = 0;
int num = 0;
boolean isNeg = false;
if (str.charAt(0) == '-')
{
isNeg = true;
i = 1;
}
while( i < str.length())
{
num *= 10;
num += str.charAt(i++) - '0';
}
if (isNeg)
{
num = -num;
}
return num;
}
}
Full code of MessengerWithFiles.java
:
import java.io.IOException;
public class MessengerWithFiles
{
public static void main(String[] args) throws IOException
{
Client client1 = null;
Server server1 = null;
for (int i = 0; i < args.length; i++)
{
if (args.length > 2)
{
client1 = new Client(args);
client1.clientRun2(args);
}
else if (args.length == 2)
{
server1 = new Server(args);
server1.serverRun2(args);
}
i=args.length + 20;
}
}
}