So I am learning about basic TCP/IP applications and I am trying to figure out a way to send text files one after another. The first line that the server reads will be the file name and then the data in the file will be read after. So I'm trying to explore ways to read until the end of the first file and then start another stream to write another file. My application freezes after the second try. So I dont know if the problem is on the client side or the server side, and I am not sure how to solve this.
I have methods for getting the connection, getting streams, closing connection, and processing connection. I am just posting the processing connection method for the server and client.
CLIENT:
private void processConnection() throws Exception
{ //read file
Path filePath = null;
try
{
filePath = Paths.get(inputpath);
fileToSend = Files.newInputStream(filePath);
reader = new BufferedReader(new InputStreamReader(fileToSend));
//send file name
output.writeObject(path);
output.flush();
//send file data
String linesToSend = reader.readLine();
while(linesToSend != null)
{
output.writeObject(linesToSend);
output.flush();
linesToSend = reader.readLine();
}
message = (String)input.readObject();
display.append("\n" + message);
}
catch(NullPointerException e)
{
display.append("\nNo file to send.");
}
}
SERVER:
private void processConnection() throws IOException
{
String message = "Connection successful";
sendData(message);
try
{
//read first line of input for file name
String clientInput = (String) input.readObject();
//create file path
String abFilePath = pathToString + "\\" + clientInput;
// create file
FileSystem fs = FileSystems.getDefault();
Path path = fs.getPath(abFilePath);
fileOutput = new BufferedOutputStream(Files.newOutputStream(path, CREATE_NEW));
writer = new BufferedWriter(new OutputStreamWriter(fileOutput));
//read rest of data
String s = (String)input.readObject();
while(s != null)
{
writer.write(s, 0, s.length());
s = (String)input.readObject();
}
writer.close();
display.append("\nFile " + clientInput + " was recieved.");
message = "\n" + clientInput + " was sent to server.";
sendData(message);
}
catch(ClassNotFoundException | SocketException e)
{
e.printStackTrace();
display.append("\nClient disconnected\n");
input = null;
}
catch(FileAlreadyExistsException e)
{
display.append("\nFile already exist.");
}
}