2016-03-06 30 views
2

我正在使用Linux,並且我有服務器從客戶端接收輸入流,並僅返回客戶端從瀏覽器請求的文件。服務器返回客戶端需要的任何文件

它編譯完美,但它沒有返回任何內容,我列出了我在結尾運行服務器並獲取文件的所有步驟。

服務器

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

public class Server { 
    public static void main(String[] args) throws IOException { 
     ServerSocket serverSocket = null; 

     try { 
      serverSocket = new ServerSocket(9999); 
     } catch (IOException ex) { 
      System.out.println("Can't setup server on this port number. "); 
     } 

     Socket socket = null; 
     InputStream in = null; 
     OutputStream out = null; 

     try { 
      socket = serverSocket.accept(); 
     } catch (IOException ex) { 
      System.out.println("Can't accept client connection. "); 
     } 

     try { 
      in = socket.getInputStream(); 
     } catch (IOException ex) { 
      System.out.println("Can't get socket input stream. "); 
     } 

     try { 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      String line = br.readLine(); 
      System.out.println("File name = " + line); 

      //Deixem nomes el nom del File o fitxer 
      String fileName = line.replace("GET /", ""); 
      fileName = fileName.replace(" HTTP/1.1", ""); 
      System.out.println("File name is" + fileName);   

      out = new FileOutputStream(fileName); 
     } catch (FileNotFoundException ex) { 
      System.out.println("File not found. "); 
     } 

     byte[] bytes = new byte[16*1024]; 

     int count; 
     while ((count = in.read(bytes)) > 0) { 
      out.write(bytes, 0, count); 
      System.out.println("Bytees "+count); 
     } 

     out.close(); 
     in.close(); 
     socket.close(); 
     serverSocket.close(); 
    } 
} 

正如你可以看到我使用的方法代替()只留下文件名。客戶端會是誰都會詢問例如文件瀏覽器:

  • 客戶希望一個文件hello.txt的localhost:9999/hello.txt
  • 服務器是在文件夾中的java/bin中使用名稱Server.class
  • 文件hello.txt的是在java /文件

這我是如何從控制檯執行我的服務器:

  • CD中的Java /文件
  • java命令../bin服務器[-p 9999]

但我不接受任何文件,爲什麼?難道我做錯了什麼??

+3

那麼你沒有在響應中寫入任何HTTP頭文件。我強烈建議不要嘗試編寫自己的HTTP服務器,當已經存在太多的HTTP服務器時...如果您想要編寫代碼以便根據需要進行響應,請將其放入現有HTTP服務器的上下文中,例如,作爲Tomcat中的servlet。 (我也注意到你寫的代碼將是一個很大的安全問題......你真的不希望客戶端能夠要求服務器上的任何*文件)。 –

回答

0

首先,通過喬恩斯基特按照建議

其次,如果你正在學習然後按照這個
writing and reading using socket

問題是,你嘗試寫不插座出流,但到文件 和當然如果你想做http服務器。你可以檢查這個simple http server question

其他問題: 你必須讀你的文件流式傳輸它,它會更好地寫入響應頭。 你的服務器將只處理一個不正確的請求。你應該忽略路徑並只允許下載特定的格式。你的try catch塊被濫用。

+0

羽絨選民你能告訴你在答案中不喜歡什麼嗎? – qwr

+0

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的重要部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/11526425) –

+0

@FrancescoMenzani如果您已閱讀所有內容,您可以看到我提到的主要問題。說明「Promblem is ..」並且添加鏈接是更好的選擇,而不是重寫他所有的代碼,這些代碼還有許多其他問題與問題無關。但我可以同意最好把它寫成評論 – qwr

相關問題