2012-05-28 10 views
22

私は現在 ...静的ページ<p>Hello!</p>を返す小さなHTTPサーバを作成しています私は、Javaでソケットを試してみました:Java/Socketを備えたシンプルなHttpサーバー?

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

     // création de la socket 
     int port = 1989; 
     ServerSocket serverSocket = new ServerSocket(port); 
     System.err.println("Serveur lancé sur le port : " + port); 

     // repeatedly wait for connections, and process 
     while (true) { 

      // on reste bloqué sur l'attente d'une demande client 
      Socket clientSocket = serverSocket.accept(); 
      System.err.println("Nouveau client connecté"); 

      // on ouvre un flux de converation 

      BufferedReader in = new BufferedReader(
          new InputStreamReader(clientSocket.getInputStream()) 
         ); 
      PrintWriter out = new PrintWriter(
         new BufferedWriter(
          new OutputStreamWriter(clientSocket.getOutputStream())), 
         true); 

      // chaque fois qu'une donnée est lue sur le réseau on la renvoi sur le flux d'écriture. 
      // la donnée lue est donc retournée exactement au même client. 
      String s; 
      while ((s = in.readLine()) != null) { 
       System.out.println(s); 


     out.write("HTTP/1.0 200 OK\r\n"); 
     out.write("Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"); 
     out.write("Server: Apache/0.8.4\r\n"); 
     out.write("Content-Type: text/html\r\n"); 
     out.write("Content-Length: 59\r\n"); 
     out.write("Expires: Sat, 01 Jan 2000 00:59:59 GMT\r\n"); 
     out.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n"); 
     out.write("\r\n"); 
     out.write("<TITLE>Exemple</TITLE>"); 
     out.write("<P>Ceci est une page d'exemple.</P>"); 
    } 

      // on ferme les flux. 
      System.err.println("Connexion avec le client terminée"); 
      out.close(); 
      in.close(); 
      clientSocket.close(); 
     } 
    } 

このコードはすべてのエラーが含まれていないと私は次のようにブラウザからの応答を得ましたこれは:

GET/HTTP/1.1 
Host: localhost:1989 
Connection: keep-alive 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5 Comodo_Dragon/19.0.3.0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Encoding: gzip,deflate,sdch 
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4 
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 

しかし、私の問題は、ブラウザにページが表示されないということですか? 助けてください?

PS:私はすでにこの記事を読んで:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol、(フランス語用イム申し訳ありません...)

答えて

29

すべてのリクエストヘッダー行の後に\ r \ nに加えて、ヘッダーの後に空の行を送信する必要があります。例:

out.write("HTTP/1.0 200 OK\r\n"); 
// Header... 
out.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n"); 
out.write("\r\n"); // The content starts afters this empty line 
out.write("<TITLE>Hello!</TITLE>"); 
// Content... 

それが動作するように私はあなたのコードを修正し(それはまだ完璧ではない、あなたがjava.util.concurrent.ThreadPoolExecutorで例えば別々のスレッドですべての要求を処理する必要があります):

public static void main(String[] args) throws Exception { 
    // création de la socket 
    int port = 1989; 
    ServerSocket serverSocket = new ServerSocket(port); 
    System.err.println("Serveur lancé sur le port : " + port); 

    // repeatedly wait for connections, and process 
    while (true) { 
     // on reste bloqué sur l'attente d'une demande client 
     Socket clientSocket = serverSocket.accept(); 
     System.err.println("Nouveau client connecté"); 

     // on ouvre un flux de converation 

     BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); 

     // chaque fois qu'une donnée est lue sur le réseau on la renvoi sur 
     // le flux d'écriture. 
     // la donnée lue est donc retournée exactement au même client. 
     String s; 
     while ((s = in.readLine()) != null) { 
      System.out.println(s); 
      if (s.isEmpty()) { 
       break; 
      } 
     } 

     out.write("HTTP/1.0 200 OK\r\n"); 
     out.write("Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"); 
     out.write("Server: Apache/0.8.4\r\n"); 
     out.write("Content-Type: text/html\r\n"); 
     out.write("Content-Length: 59\r\n"); 
     out.write("Expires: Sat, 01 Jan 2000 00:59:59 GMT\r\n"); 
     out.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n"); 
     out.write("\r\n"); 
     out.write("<TITLE>Exemple</TITLE>"); 
     out.write("<P>Ceci est une page d'exemple.</P>"); 

     // on ferme les flux. 
     System.err.println("Connexion avec le client terminée"); 
     out.close(); 
     in.close(); 
     clientSocket.close(); 
    } 
} 
+1

私はこれを試しましたが、まだ動作していません...(私の更新を参照)。 –

+0

ループが間違っている間にリクエストヘッダが読み込まれます。私は私の答えに実際の例を追加します。 –

+0

あなたの例では、Joelはoutputstreamをフラッシュするのを忘れていました。 HTMLをたくさん使ってこのコードを試しても、正しく動作しません。 –

1

あなたはどのようなマシンを使用していますか?どのようなOSですか? UNIXマシンを実行している場合は、LF文字のみを送信するためprintlnは機能しません。 HTTPでは、ヘッダーにCRとLFが必要です。 \ rを文字列の最後に追加して、それが機能するかどうか確認してください。

ああ、また、お使いの:

out.println("HTTP/1.0 200 OK"+ 
"Date: Fri, 31 Dec 1999 23:59:59 GMT"+ 
"Server: Apache/0.8.4"+ 
"Content-Type: text/html"+ 
"Content-Length: 59"+ 
"Expires: Sat, 01 Jan 2000 00:59:59 GMT"+ 
"Last-modified: Fri, 09 Aug 1996 14:21:40 GMT"+ 

それは、単一の、長い文字列を印刷しています。

各文字列のprintlnに変更するか、\ r \ nを文字列に追加してください。

+0

ありがとうございます!私はWindows7を持っていますが、これを試しましたが、まだ動作しません。 –

+0

=> out.flush(); –

1

各ライン出力の間に正しいラインセパレータ(\r\n)が必要です。それらを連結するだけでは不十分です。応答を印刷するかどうかはわかります。

+0

彼は\ r \ nが必要です。これはHTTPです。 – EJP

4

これはあなたの最後の質問に対する回答であり、ブラウザで何も表示されない理由は、文字数が正しく計算されなかったためです。それは57の代わりに、59

良いはず

はまだ自動的に計算された文字数を持っていることですが、私はあなたのサンプルがちょうどサンプルであると信じています。

+1

まあ、それは私のために働いた。それは上にする必要があります:) –

関連する問題