2012-10-15 87 views
-4

嗨,我的服务器出现问题,每当我打电话“下载”文件下载但我不能使用其他命令我有,因为他们返回为空。任何人都可以在代码中看到问题?返回的消息为空

服务器:

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) { 
     } 
    } 
} 

客户:

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) { 

    } 

} 
} 
+0

有* *没有其他命令你有**。 –

+0

哪些命令? – maxhax

+0

第一个问题:'baos.write(aByte)'应该是'baos.Write(aByte,0,bytesRead)'。这也不清楚为什么你有'baos',当你只能一直写'bos' ... –

回答

0

调试你的代码,有两个提示:

1)

不surpress你例外。处理它们!第一步将打印你的堆栈跟踪,这个问题就不会被打开;-)调试你的代码!

2)

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

所以在你的第二个呼叫服务器端的插座就已经被关闭。

+0

如果我不关闭套接字,dload命令将不再工作,如果我关闭它,我只能运行一次,所以我不知道该怎么办。 –

+0

@ user1746749 http://stackoverflow.com/questions/3428127/close-java-socket – maxhax

0

第一件事:

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

这可以抛出一个NumberFormatException异常,并且因为ARGS [0]是由用户通过你应该处理这个问题。 阅读代码这也给了我一个问题:

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

抛出NumberFormatException异常的时候,我给C2F作为命令到服务器。您明确需要在你的代码的任何地方处理这个异常,并给客户给予适当的回答,是这样的:

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

(简称例如,从本周开始,你必须放大的代码)


while (isConnected == true) { 

我看不到它!为什么不使用这个?

while (isConnected) { 

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

可以是:

if("sum".equalsIgnoreCase(msgFromClient)){ 
在这种情况下,你必须与NullPointerException异常没有问题

。 (如果msgFromClient为null,则该语句为false)。


顺便说一下,日期和时间命令对我来说工作正常。检查其他人。

要解决DLOAD我认为你必须要删除的行:

outToClient.close(); 

(编辑:抱歉maxhax为同一answr,没有看到你的答案写这篇)

+0

感谢您花时间检查代码,我用dload的问题是,如果我删除outToClient.close();该文件将不会被下载。在这个问题停留在那一刻,而不是确定处理它:( –

+0

如何尝试 ObjectOutputStream的OOS =新的ObjectOutputStream(socket.getOutputStream()); 或尝试在关闭的OutputStream – Gianmarco

+0

后重新连接一个新的socket谢谢你,我做了这样的服务器和客户端重新连接,每次我使用卸载,所以它现在的作品:) –