-4

Hi i have a problem with my server, everytime i call "dload" the file gets downloaded but i can't use the other commands i have because they get returned as null. Anyone who can see the problem in the code?

Server :

public class TCPServer {

    public static void main(String[] args) {

        ServerSocket server = null;
        Socket client;
        // Default port number we are going to use
        int portnumber = 1234;
        if (args.length >= 1) {
            portnumber = Integer.parseInt(args[0]);
        }
        // Create Server side socket
        try {
            server = new ServerSocket(portnumber);
        } catch (IOException ie) {
            System.out.println("Cannot open socket." + ie);
            System.exit(1);
        }
        System.out.println("ServerSocket is created " + server);
        // Wait for the data from the client and reply

        boolean isConnected = true;

        try {
            // Listens for a connection to be made to
            // this socket and accepts it. The method blocks until
            // a connection is made
            System.out.println("Waiting for connect request...");
            client = server.accept();
            System.out.println("Connect request is accepted...");
            String clientHost = client.getInetAddress().getHostAddress();
            int clientPort = client.getPort();
            System.out.println("Client host = " + clientHost
                    + " Client port = " + clientPort);

            // Read data from the client
            while (isConnected == true) {

                InputStream clientIn = client.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        clientIn));
                String msgFromClient = br.readLine();
                System.out.println("Message received from client = "
                        + msgFromClient);

                // Send response to the client

                if (msgFromClient != null
                        && msgFromClient.equalsIgnoreCase("sum")) {
                    OutputStream clientOut = client.getOutputStream();
                    PrintWriter pw = new PrintWriter(clientOut, true);
                    Double[] list;
                    list = new Double[5];
                    String value;
                    int i;
                    try {

                        for (i = 0; i < 5; i++) {
                            pw.println("Input number in arrayslot: " + i);
                            value = br.readLine();
                            double DoubleValue = Double.parseDouble(value);
                            list[i] = DoubleValue;
                        }
                        if (i == 5) {
                            Double sum = 0.0;
                            for (int k = 0; k < 5; k++) {
                                sum = sum + list[k];
                            }
                            pw.println("Sum of array is " + sum);
                        }
                    } catch (NumberFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                if (msgFromClient != null
                        && msgFromClient.equalsIgnoreCase("max")) {
                    OutputStream clientOut = client.getOutputStream();
                    PrintWriter pw = new PrintWriter(clientOut, true);
                    Double[] list;
                    list = new Double[5];
                    String value;
                    int i;
                    try {

                        for (i = 0; i < 5; i++) {
                            pw.println("Input number in arrayslot: " + i);
                            value = br.readLine();
                            double DoubleValue = Double.parseDouble(value);
                            list[i] = DoubleValue;
                        }
                        if (i == 5) {
                            Arrays.sort(list);
                            pw.println("Max integer in array is " + list[4]);
                        }
                    } catch (NumberFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                if (msgFromClient != null
                        && msgFromClient.equalsIgnoreCase("time")) {
                    OutputStream clientOut = client.getOutputStream();
                    PrintWriter pw = new PrintWriter(clientOut, true);
                    Calendar calendar = GregorianCalendar.getInstance();
                    String ansMsg = "Time is:, "
                            + calendar.get(Calendar.HOUR_OF_DAY) + ":"
                            + calendar.get(Calendar.MINUTE);
                    pw.println(ansMsg);
                }
                if (msgFromClient != null
                        && msgFromClient.equalsIgnoreCase("date")) {
                    OutputStream clientOut = client.getOutputStream();
                    PrintWriter pw = new PrintWriter(clientOut, true);
                    Calendar calendar = GregorianCalendar.getInstance();
                    String ansMsg = "Date is: " + calendar.get(Calendar.DATE)
                            + "/" + calendar.get(Calendar.MONTH) + "/"
                            + calendar.get(Calendar.YEAR);
                    ;
                    pw.println(ansMsg);
                }
                if (msgFromClient != null
                        && msgFromClient.equalsIgnoreCase("c2f")) {
                    OutputStream clientOut = client.getOutputStream();
                    PrintWriter pw = new PrintWriter(clientOut, true);
                    String celciusValue;
                    boolean ifRead = false;

                    try {

                        pw.println("Input celcius value");
                        celciusValue = br.readLine();
                        ifRead = true;
                        if (ifRead == true) {
                            double celcius = Double.parseDouble(celciusValue);
                            celcius = celcius * 9 / 5 + 32;

                            pw.println(celcius);
                        }
                    } catch (NumberFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                if (msgFromClient != null
                        && msgFromClient.equalsIgnoreCase("dload")) {

                    OutputStream outToClient = client.getOutputStream();
                    if (outToClient != null) {
                        File myFile = new File("C:\\ftp\\pic.png");
                        byte[] mybytearray = new byte[(int) myFile.length()];

                        FileInputStream fis = new FileInputStream(myFile);

                        BufferedInputStream bis = new BufferedInputStream(fis);

                        try {
                            bis.read(mybytearray, 0, mybytearray.length);
                            outToClient.write(mybytearray, 0,
                                    mybytearray.length);

                            outToClient.flush();
                            outToClient.close();
                            bis.close();
                            fis.close();

                        } catch (IOException ex) {
                            // Do exception handling
                        }

                        System.out.println("test");

                    }
                }

                if (msgFromClient != null
                        && msgFromClient.equalsIgnoreCase("quit")) {
                    client.close();
                    break;
                }
                // if (msgFromClient != null
                // && !msgFromClient.equalsIgnoreCase("bye")) {
                // OutputStream clientOut = client.getOutputStream();
                // PrintWriter pw = new PrintWriter(clientOut, true);
                // String ansMsg = "Hello, " + msgFromClient;
                // pw.println(ansMsg);
                // }

                // Close sockets
                if (msgFromClient != null
                        && msgFromClient.equalsIgnoreCase("bye")) {
                    server.close();
                    client.close();
                    break;
                }

                msgFromClient = null;
            }
        } catch (IOException ie) {
        }
    }
}

Client:

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

public class TCPClient {
 public static void main(String args[]) {

  boolean isConnected = true;
  Socket client = null;
  int portnumber = 1234; // Default port number we are going to use
  if (args.length >= 1) {
   portnumber = Integer.parseInt(args[0]);
  }
  try {

   String msg = "";
   // Create a client socket
   client = new Socket("127.0.0.1", 1234);
   System.out.println("Client socket is created " + client);
   // Create an output stream of the client socket

   OutputStream clientOut = client.getOutputStream();
   PrintWriter pw = new PrintWriter(clientOut, true);
   // Create an input stream of the client socket
   InputStream clientIn = client.getInputStream();
   BufferedReader br = new BufferedReader(new InputStreamReader(
     clientIn));
   // Create BufferedReader for a standard input
   BufferedReader stdIn = new BufferedReader(new InputStreamReader(
     System.in));

   while (isConnected == true) {
    System.out
      .println("Commands: \n1. TIME\n2. DATE\n3. C2F\n4. MAX\n5. SUM\n6. DLOAD\n7. QUIT");
    // Read data from standard input device and write it
    // to the output stream of the client socket.
    msg = stdIn.readLine().trim();
    pw.println(msg);
    // Read data from the input stream of the client socket.



    if (msg.equalsIgnoreCase("dload")) {
        byte[] aByte = new byte[1];
        int bytesRead;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (clientIn != null) {



            try {
                FileOutputStream fos = new FileOutputStream("C:\\ftp\\pic.png");
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                bytesRead = clientIn.read(aByte, 0, aByte.length);

                do {
                    baos.write(aByte, 0, bytesRead);
                    bytesRead = clientIn.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();

                System.out.println("File is successfully downloaded to your selected directory"+ "\n" +"*-----------------*"+ "\n" );

            } catch (IOException ex) {
                System.out.println("Couldn't dowload the selected file, ERROR CODE "+ex);
            }

        }
    }else{

        System.out.println("Message returned from the server = "
                  + br.readLine());
    }
    if (msg.equalsIgnoreCase("bye")) {

     pw.close();
     br.close();
     break;
    }
   }
  } catch (Exception e) {

  }

 }
}
enoze
  • 35
  • 2
  • 8
  • There are **no other commands you have**. – Marko Topolnik Oct 15 '12 at 10:33
  • First problem: `baos.write(aByte)` should be `baos.Write(aByte, 0, bytesRead)`. It's also not clear why you've got `baos` at all, when you could just write to `bos` the whole time... – Jon Skeet Oct 15 '12 at 10:33
  • 2
    Your question seems to be saying: "Here's the code which works; what's wrong with my other code, which doesn't work?" That's like a mother with two sons taking the healthy one to the doctor and expecting the doctor to diagnose what's wrong with the one who's sick at home. – Jon Skeet Oct 15 '12 at 10:34
  • The server part is only working 1 time then i get null. – enoze Oct 15 '12 at 10:36
  • what's getting null? pasting stacktrace, more code to communication between server/client will be helpfull.. – maxstreifeneder Oct 15 '12 at 10:46
  • why you do not put the server in a runnable class? – Gianmarco Oct 15 '12 at 11:03

2 Answers2

0

debugged your code and have two hints:

1)

don't surpress your exceptions. handle them! first step would to print your stacktrace and this question on SO wouldn't ever be opened ;-) debug your code!

2)

outToClient.flush();
outToClient.close(); //is closing the socket implicitly
bis.close();
fis.close();

so in your second call the socket on server-side will already be closed.

maxstreifeneder
  • 625
  • 1
  • 8
  • 19
  • If i don't close the socket the dload command won't work a second time and if i close it i can only run it one time so i don't know what to do. – enoze Oct 15 '12 at 11:40
0

first thing:

if (args.length >= 1) {
    portnumber = Integer.parseInt(args[0]);
}

This can throw a NumberFormatException, and because args[0] is passed by the user you should handle this. reading the code also this gave me a problem:

double DoubleValue = Double.parseDouble(value); // LINE 104

Throwing a NumberFormatException when I give c2f as command to the server. You definitively need to handle this exception anywhere in your code and give proper answer to the client, something like:

try{
    double DoubleValue = Double.parseDouble(value);
}catch(NumberFormatException e){
    // TELL THE CLIENT "ops, the number you inserted is not a valid double numer
}

(in short example, starting from this you have to enlarge the code)


while (isConnected == true) {

I cannot see it! why not use this?

while (isConnected) {

if (msgFromClient != null && msgFromClient.equalsIgnoreCase("sum")){

can be:

if("sum".equalsIgnoreCase(msgFromClient)){

in this case you have no problem with the NullPointerException. (if msgFromClient is null the statement is false).


By the way, date and time command are working fine for me. Check the others.

To fix dload i think you have to delete the line:

outToClient.close();

(EDIT: sorry to maxhax for the same answr, didn't see your answer while writing this)

Gianmarco
  • 2,536
  • 25
  • 57
  • Thanks for taking your time to check the code, the problem i have with dload is that if i remove outToClient.close(); the file will not be downloaded. Stuck at this problem at the moment and not sure how the handle it :(. – enoze Oct 15 '12 at 12:02
  • try with ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); or try to reconnect a new socket after you close the outputStream – Gianmarco Oct 15 '12 at 12:16
  • Thanks man, i made it so that the server and client reconnects everytime i use the dload so it works now :) – enoze Oct 15 '12 at 13:00