0

Screenshot of running program (server on left client on right)

enter image description here

The issue with the above screenshot is that the left window (server) outputs "null" instead of executing the correct output for this line: System.out.println("File " + filename + " downloaded (" + current + " bytes read)");

The flow of file transfer communications happens as follows:

The server user types "f", server presses enter, server types the filename (in this case it was test.txt), server presses enter, client receives filename, client sends file to server, server receives file, server outputs the print line.

My question is: What changes can I make to the following code so that it will execute the correct output for that print line?

Here is the code of receiving it on the server side

 public void SendFileName() throws FileNotFoundException
 {
        try
        {

                //Send the message to the client
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);

                 //creating message to send from standard input
                 String newmessage = "";

                 // input the message from standard input
                 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 maxsize = 9999;
                 int bytesRead;
                 int current = 0;
                 FileOutputStream fos = null;
                 BufferedOutputStream bos = null;
                 Socket sock = null;

                 // receive file
                 byte [] mybytearray  = new byte [maxsize];
                 InputStream is = sock.getInputStream();
                 fos = new FileOutputStream(filename);
                 bos = new BufferedOutputStream(fos);
                 bytesRead = is.read(mybytearray,0,mybytearray.length);
                 current = bytesRead;

                 while(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();
                // runClientRead(clientArgs);
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }

Here is the code of sending it on the client side

import java.io.*;
import java.net.Socket;

public class ClientReceive extends Thread
{

    Socket clientSocket;
    boolean m_bRunThread = true; 
    boolean ServerOn = true;
    int gotPortNumber = 0;
    public ClientReceive(Socket s) throws FileNotFoundException
    { 
        //super(); 
        clientSocket = s;
    } 
    public void run()
    {
        while(true)
        {
            try
            {
                    BufferedReader readFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    String fromServer = readFromServer.readLine();
                    if(fromServer.contains("filenameistotheright->` ") == true)
                    {
                        String[] parts = fromServer.split(" ");
                        String nonsense = parts[0];
                        String filename = parts[1];
                        System.out.println("Requested filename is: " + filename);


                        //sending file

                        FileInputStream fis = null;
                        BufferedInputStream bis = null;
                        OutputStream os = null;

                        File myFile = new File(filename);
                        byte [] mybytearray  = new byte [(int)myFile.length()];
                        fis = new FileInputStream(myFile);
                        bis = new BufferedInputStream(fis);
                        bis.read(mybytearray,0,mybytearray.length);
                        os = clientSocket.getOutputStream();
                        System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)");
                        os.write(mybytearray,0,mybytearray.length);
                        os.flush();

                    }
                    else
                    {
                        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);
                        String numberPart = a.substring(i);
                        System.out.println("Recieved from server: " + alphaPart +"\n");


                        if(fromServer.equals(null))
                        {
                            System.exit(0);
                        }

                    }
                    if(fromServer.equals(null))
                    {
                    System.exit(0);
                    }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {

            }
        }
    }
}

TL;DR: If you know the solution by this line, SKIP reading the rest of the code below and scroll down to answer, there are 8 classes in total

Main function file:

import java.io.*;

public class Main
{
    public static void main(String[] args) throws IOException, FileNotFoundException
    {

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

}

Server file:

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 
    {
        // set the instance variable

        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(); 

                   // input the message from standard input
                   BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));

                   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 )
               {
                   System.out.println( e.getMessage() );
               }
            }
        }
    };


public void StandardOutput()
{
        try
        {           
            //Send the message to the client
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            //creating message to send from standard input
            String newmessage = "";
            try 
            {
                System.out.println("Enter your message: ");
                // input the message from standard input
                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();
            System.out.println("Message sent to client: "+sendMessage);
            StandardInput();
            //run();
            } 
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {

            }

}
public void SendFileName() throws FileNotFoundException
{
    try
    {

            //Send the message to the client
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

             //creating message to send from standard input
             String newmessage = "";

             // input the message from standard input
             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 maxsize = 9999;
             int bytesRead;
             int current = 0;
             FileOutputStream fos = null;
             BufferedOutputStream bos = null;
             Socket sock = null;

             // receive file
             byte [] mybytearray  = new byte [maxsize];
             InputStream is = sock.getInputStream();
             fos = new FileOutputStream(filename);
             bos = new BufferedOutputStream(fos);
             bytesRead = is.read(mybytearray,0,mybytearray.length);
             current = bytesRead;

             while(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();
            // runClientRead(clientArgs);
    }
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}
void FileTransferSend()
{
    //connect to the filetransfer



    try
    {   
        System.out.println("Which file do you want? ");
        Scanner scanner = new Scanner(System.in);
        String filename = scanner.nextLine();
        FileInputStream fis = new FileInputStream(new File(filename));
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(fileSocket.getOutputStream()));
        int element;
        while((element = fis.read()) !=1)
        {
            dos.write(element);
        }
        byte[] byteBuffer = new byte[1024]; // buffer

        while(fis.read(byteBuffer)!= -1)
        {
            dos.write(byteBuffer);
        }
        OutputOptions();


       // dos.close();
       // fis.close();
    } 
    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 StandardInput()
{
    OutputOptions();
    while(true)
    {

        try 
        {
           // input the message from standard input
           BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
           String line2 = "";

           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 )
       {
           System.out.println( e.getMessage() );
       }
        finally
        {

        }
    }

}




}

Server Recieving Thread 1:

import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class ServerRecieve extends Thread 
{
    int filePortNumber = 0;
    Socket servSocket;
    Socket fileSocket;
    boolean m_bRunThread = true; 
    boolean ServerOn = true;
    int gotPortNumber = 0;
    int once = 0;
    String fileNameGlobal = "";

    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("filenameistotheright->` ") == true)
                {
                    String[] parts = fromClient.split(" ");
                    final String filename = parts[1];
                    System.out.println("Requested filename is: " + filename);
                    fileNameGlobal = filename;
                    //Sending the file
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    OutputStream os = null;

                    File myFile = new File(filename);
                    byte [] mybytearray  = new byte [(int)myFile.length()];
                    fis = new FileInputStream(myFile);
                    bis = new BufferedInputStream(fis);
                    bis.read(mybytearray,0,mybytearray.length);
                    os = servSocket.getOutputStream();
                    System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)");
                    os.write(mybytearray,0,mybytearray.length);
                    os.flush();

                }
                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("Recieved from client: " + alphaPart +"\n");
                    if(gotPortNumber == 0)
                    {
                        String[] parts1 = fromClient.split(" ");
                        String nonsense1 = parts1[0];
                        String filename1 = parts1[1];
                        System.out.println("File transfer port found: " + numberPart + "\n");
                        gotPortNumber = 3;
                        filePortNumber = Integer.parseInt(numberPart);
                        int p = 0;
                        p = strToInt(numberPart);

                        System.out.println(filename1);
                        //starting the recieving thread

                        if(once == 0)
                        {
                            String[] parts12 = fromClient.split(" ");
                            String nonsense12 = parts12[0];
                            String filename31 = parts12[1];
                            //System.out.println("name:" + filename31);
                            String address = "localhost";
                         //   fileSocket = new Socket(address, p);
                            //ServerSocket serverSocket1 = new ServerSocket(p);
                            if((filename31.equals(null) == true) && (!filename31.equals("")==true))
                            {
                                ServerFile getServerFile = new ServerFile(servSocket, p, filename31);
                                getServerFile.start(); 
                            }

                            once = 4;
                        }
                        once = 4;
                    }
                    gotPortNumber = 3;


                    if(fromClient.equals(null))
                    {
                        System.exit(0);
                    }
                    OutputOptions();
                }
            }
            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;

        //Check for negative sign; if it's there, set the isNeg flag
        if (str.charAt(0) == '-') {
            isNeg = true;
            i = 1;
        }

        //Process each character of the string;
        while( i < str.length()) {
            num *= 10;
            num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
        }

        if (isNeg)
            num = -num;
        return num;
    }
}

Server Recieving Thread 2:

import java.net.Socket;
import java.io.*;
import java.util.*;
public class ServerFile extends Thread
{
    public Socket servingSocket = null;
    public int FilePort = 0;
    public String otherName = "";
    public ServerFile(Socket ok, int port, String FileName) throws FileNotFoundException
    {
          this.FilePort = port;
          this.servingSocket = ok;
          this.otherName = FileName;
    }
    public void run()
    {
        while(true)
        {

            try
            {
                int maxsize = 999999;
                byte[] buffer = new byte[maxsize];
                //servingSocket = new Socket("localhost", FilePort);
                InputStream is = servingSocket.getInputStream();
                File test = new File(otherName);
                test.createNewFile();
                FileOutputStream fos = new FileOutputStream(test);
                BufferedOutputStream out = new BufferedOutputStream(fos);
                int byteread = is.read(buffer, 0, buffer.length);
                int current = byteread;
                buffer = new byte[16384];

                while ((byteread = is.read(buffer, 0, buffer.length)) != -1) 
                {
                  out.write(buffer, 0, byteread);
                }
                out.flush();

                    //socket.close();
                   // fos.close();
                  //  is.close();


            } catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {

            }

        }
    }    
}

Client code with full context: https://www.dropbox.com/s/x2pjlw2wcgn8lhd/newcode.zip?dl=0

hey
  • 33
  • 6

1 Answers1

1

You have an exception there.

You have a pokemon catch (catch (Exception e) which is "catch all") in your Server file. That pokemon catch just prints the exception message, not its stack trace. An exception's message can be null, and that's the null you see.

Now, whence comes that null? Well, you have:

Socket sock = null;

// receive file
byte [] mybytearray  = new byte [maxsize];
InputStream is = sock.getInputStream();

Well, if sock is null, you can't get sock.getInputStream(). You get a NullPointerException. That gets caught in your catch-them-all and it probably doesn't have a message.

  • Avoid pokemon catches.
  • Always print the stack trace, not the message.
  • Give your sock a real value.
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79