0

I am a new java programmer and I have a file sharing program which I am trying to make it work continuously in a while(true) loop in a multithread. I have the sever running correctly but I can make the client to run continuously e.g. server establishes connection then I run client but I have to manually run it because after a file is transfer, client stops. Bellow is the code, can you please help me correct the error?

import java.net.*;
import java.io.*;
public class TCPServer
{
private static ServerSocket myServer;
private static Socket myClient = null;

public static void main(String[] args) throws IOException
{

    try
    {
        myServer = new ServerSocket(6789);
        System.out.println("Server is now available...");
    }
    catch(Exception e)
    {
        System.err.println("This port is unavailable.");
        System.exit(1);
    }

    while(true)
    {
        try
        {
            myClient = myServer.accept();
            System.out.println("Connection established to : " + myClient);
            Thread t = new Thread(new ConnectionThread(myClient));
            t.start();
        }catch(Exception e)
        {
            System.err.println("Connection failed...!");
        }
    }
}
}

import java.net.*;
import java.io.*;
public class TCPClient
{
private static BufferedReader myReader;
private static PrintStream myOut;
private static String fileName;
private static Socket mySocket;

public static void main(String[] args) throws IOException
{
    try
    {
        mySocket = new Socket("localhost", 6789);
        myReader = new BufferedReader(new InputStreamReader(System.in));
    }
    catch(Exception e)
    {
        System.err.println("Couldn't establish a connection with server.");
        System.exit(1);
    }
    try
    {

        myOut = new PrintStream(mySocket.getOutputStream());
        switch (Integer.parseInt(sendOrReceive()))
        {
            case 1:
                    myOut.println("1");
                    sendFile();
                    break;
            case 2:
                    myOut.println("2");
                    System.err.print("Enter file name: ");
                    fileName = myReader.readLine();
                    myOut.println(fileName);
                    receiveFile(fileName);
                    break;
        }
        mySocket.close();
    }
    catch(Exception e)
    {
        System.err.println("not valid input");
    }
}

public static String sendOrReceive() throws IOException
{
    System.out.println("1. Send file.");
    System.out.println("2. Recieve file.");
    System.out.print("\nMake selection: ");

    return myReader.readLine();
}

public static void sendFile()
{
    try
    {
        System.err.print("Enter file name: ");
        fileName = myReader.readLine();
        File myFile = new File("F:/" + fileName);
        byte[] myArray = new byte[(int) myFile.length()];

        FileInputStream myInFileStream = new FileInputStream(myFile);
        BufferedInputStream myBufferStream = new BufferedInputStream(myInFileStream);

        DataInputStream myDataIn = new DataInputStream(myBufferStream);
        myDataIn.readFully(myArray, 0, myArray.length);

        OutputStream myOutStream = mySocket.getOutputStream();

        //Sending file name and file size to the server
        DataOutputStream myDataOut = new DataOutputStream(myOutStream);
        myDataOut.writeUTF(myFile.getName());
        myDataOut.writeLong(myArray.length);
        myDataOut.write(myArray, 0, myArray.length);
        myDataOut.flush();
        System.out.println("The file " + fileName + " was sent to the server.");
    }
    catch (Exception e)
    {
        System.err.println("The file " + fileName + " was not found!");
    }
}

public static void receiveFile(String fileName)
{
    try
    {
        InputStream myIn = mySocket.getInputStream();
        DataInputStream myDataOut = new DataInputStream(myIn);
        fileName = myDataOut.readUTF();
        OutputStream myOut = new FileOutputStream(("F:/" + fileName));
        long file =  myDataOut.readLong();
        byte[] buffer = new byte[1024];
        int num = 0;
        while (file  > 0 && num != -1)
        {
            num =  myDataOut.read(buffer, 0, (int) Math.min(buffer.length, file));
            myOut.write(buffer, 0, num);
            file  -= num;
        }
        myOut.close();
        myIn.close();
        myDataOut.close();
        System.out.println("The file " + fileName + " was received from the server.");
    }
    catch(IOException ex)
    {
        System.err.println("Connection closed.");
    }
}
}

public class ConnectionThread implements Runnable
{
private Socket clientSocket;
private BufferedReader myBuffer = null;

public ConnectionThread(Socket aSocket)
{
    this.clientSocket = aSocket;
}

@Override
public void run()
{
    try
    {

        myBuffer = new BufferedReader(new InputStreamReader(
                clientSocket.getInputStream()));
        String choice = "";
        while((choice = myBuffer.readLine()) != null)
        {
            switch (choice)
            {
                case "1":
                            receiveFile();
                            break;
                case "2":
                            String fileName;
                            while ((fileName = myBuffer.readLine()) != null)
                            {
                                sendFile(fileName);
                            }
                            break;
                 default:
                            System.out.println("Not a valid choice. Choice must be '1' or '2'.");
                            break;
            }
            myBuffer.close();
            clientSocket.close();
            break;
        }
    }
    catch(IOException e)
    {
         e.printStackTrace();
    }
}

public void receiveFile()
{
    try
    {
        DataInputStream myDataOut = new DataInputStream(clientSocket.getInputStream());
        String fileName = myDataOut.readUTF();
        FileOutputStream myOut = new FileOutputStream(("C:/SHARED/" + fileName));
        long file = myDataOut.readLong();
        byte[] buffer = new byte[1024];
        int num = 0;
        while (file  > 0 && num != -1)
        {
            num = myDataOut.read(buffer, 0, (int) Math.min(buffer.length, file));
            myOut.write(buffer, 0, num);
            file -= num;
        }
        myOut.close();
        myDataOut.close();
        System.out.println("The file " + fileName + " was received from the client.");
    }catch (IOException e)
    {
        System.err.println("Connection closed.");
    }
}

public void sendFile(String fileName)
{
    try
    {
        //handle file read
        File myFile = new File("C:/Users/" + fileName);
        byte[] myArray = new byte[(int) myFile.length()];

        FileInputStream myInFileStream = new FileInputStream(myFile);
        BufferedInputStream myInBufferStream = new BufferedInputStream(myInFileStream);

        DataInputStream myDataIn = new DataInputStream(myInBufferStream);
        myDataIn.readFully(myArray, 0, myArray.length);

        //handle file send over socket
        OutputStream myOutStream = clientSocket.getOutputStream();

        //Sending file name and file size to the server
        DataOutputStream myDataOut = new DataOutputStream(myOutStream);
        myDataOut.writeUTF(myFile.getName());
        myDataOut.writeLong(myArray.length);
        myDataOut.write(myArray, 0, myArray.length);
        myDataOut.flush();
        System.out.println("The file " + fileName + " was sent to the client.");
    }
    catch(Exception e)
    {
        System.err.println("The file " + fileName + " was not found!");
    } 
}
}
1
  • 2
    Have you tried adding a loop to your client implementation? Commented Jun 13, 2014 at 9:55

4 Answers 4

1

I think you can just add a loop to your client's main, as Saket already said in a comment:

public static void main(String[] args) throws IOException
{
    while(true) {
        try
        {
            mySocket = new Socket("localhost", 6789);
            myReader = new BufferedReader(new InputStreamReader(System.in));
        }
        ...
        ...
    }
}

You could add an option '3' to end the loop and client program:

case 3:
    System.exit(0);

Threads would be needed if you wanted to download more than one file at a time with a single client.

Sign up to request clarification or add additional context in comments.

Comments

1

Your code is hard to read but key problem is:

ConnectionThread 

@Override
public void run()
{
    try
    {
...
}
}

you should try add while(true) below try:

@Override
public void run()
{
    try
    {
      while(true) {
         myBuffer = new BufferedReader(new InputStreamReader(
                clientSocket.getInputStream()));
        String choice = "";
        while((choice = myBuffer.readLine()) != null)

        ....
          // remove close client connection
      }
    }
     catch(Exception e)
    {
        System.err.println("The file " + fileName + " was not found!");
    } 
}
}

3 Comments

Thanks @hoang but it still doesn't work, I even tried the that in the TCPClient try block, but my problem persists.
Hi @mambo Do not close connection: clientSocket.close();
Hi @hoang no luck same problem, you think I have to call a tread in client as well?
1

@mambo: In TCPClient, do not close connection, using while(true)

public class TCPClient

public static void main(String[] args) throws IOException
try
    {
        mySocket = new Socket("localhost", 6789);
        myReader = new BufferedReader(new InputStreamReader(System.in));
    }
    catch(Exception e)
    {
        System.err.println("Couldn't establish a connection with server.");
        System.exit(1);
    }
    while(true) {
    .....
    }

Comments

0

There are problems at 2 classes:

  1. in TCPClient

    myOut = new PrintStream(mySocket.getOutputStream());
    switch (Integer.parseInt(sendOrReceive()))
    {
        case 1:
                myOut.println("1");
                sendFile();
                break;
        case 2:
                myOut.println("2");
                System.err.print("Enter file name: ");
                fileName = myReader.readLine();
                myOut.println(fileName);
                receiveFile(fileName);
                break;
    }
    mySocket.close();
    

The switch block work for only one choice, and later on mySocket will close.

  1. In ConnectionThread Class

in while loop,

        myBuffer.close();
        clientSocket.close();
        break;

Here clientSocket will close in first attempt only. It should be outside of while.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.