간단한 HTTP Post Server, Client 만들기.

rain의 이미지

HTTP post message를 보내는 간단한 client
HTTP post message를 받아서 출력하고 간단히 응답하는 server를 하나씩 만들어 왔습니다.
그런데 서버 쪽에서 HTTP header를 받고 나서 data를 어떻게 받는지 모르겠습니다. 전 read()를 계속하면 HTTP의 BODY에 있는 data까지 읽을 수 있을 줄 알았는데 그게 아닌가 보네요.

Server:

     40             while (true) {
     41
     42                 Socket connection = null;
     43                 try {
     44                     connection = server.accept();
     45                     OutputStream out = new BufferedOutputStream(
     46                             connection.getOutputStream());
     47                     InputStream in   = new BufferedInputStream(
     48                             connection.getInputStream());
     49
     50                     // read the first line only; that's all we need
     51                     System.out.println("Rqeuest:");
     52
     53                     StringBuffer request = new StringBuffer(80);
     54
     55                     int c;
     56                     while ((c = in.read()) != -1) {
     57                         System.out.write((char) c);
     58                     }
     59
     60                     System.out.println("\nResponse:");
     61                     System.out.write(this.header);
     62                     System.out.println();
     63                     System.out.write(this.content);
     64
     65                     // If this is HTTP/1.0 or later send a MIME header
     66                     if (request.toString().indexOf("HTTP/") != -1) {
     67                         out.write(this.header);
     68                     }
     69
     70                     out.write(this.content);
     71                     out.flush();
     72                 }  // end try
     73                 catch (IOException e) {
     74                     e.printStackTrace();
     75                 }
     76                 finally {
     77                     if (connection != null) connection.close();
     78                 }
     79
     80             } // end while

Client:

      7     public static void main(String[] args) {
      8         try {
      9             // Construct data
     10             String data =
     11                 URLEncoder.encode("id", "UTF-8") + "=" +
     12                 URLEncoder.encode("tdev_java", "UTF-8");
     13
     14             data += "&" + URLEncoder.encode("passwd", "UTF-8") + "=" +
     15                 URLEncoder.encode("789632", "UTF-8");
     16
     17             // Create a socket to the host
     18             // String hostname = "wap2.samsungmobile.com";
     19             String hostname = "localhost";
     20             int port = 80;
     21             InetAddress addr = InetAddress.getByName(hostname);
     22             Socket socket = new Socket(addr, port);
     23
     24             // Send header
     25             // String path = "/test/tdev/LoginExec.jsp";
     26             String path = "";
     27             BufferedWriter wr = new BufferedWriter(
     28                     new OutputStreamWriter(
     29                         socket.getOutputStream(), "UTF8"));
     30
     31             // Get response
     32             BufferedReader rd = new BufferedReader(
     33                     new InputStreamReader(socket.getInputStream()));
     34
     35             // Write post message
     36             wr.write("POST "+ path + " HTTP/1.0\r\n");
     37             wr.write("Content-Length: "+data.length()+"\r\n");
     38             wr.write("Content-Type: application/x-www-form-urlencoded\r\
        n");
     39             wr.write("\r\n");
     40
     41             // Send data
     42             System.out.println("Write data...");
     43             wr.write(data);
     44             wr.flush();
     45
     46             // Read response from server
     47             System.out.println("Read response...");
     48             String line;
     49             while ((line = rd.readLine()) != null)
     50                 System.out.print(line);
     51
     52             wr.close();
     53             rd.close();
     54         } catch (Exception e) {
     55             e.printStackTrace();
     56         }
     57     }
iolo의 이미지

rain wrote:

Server:
     59
     60                     System.out.println("\nResponse:");
     61                     System.out.write(this.header);
     62                     System.out.println();
     63                     System.out.write(this.content);
     64
     65                     // If this is HTTP/1.0 or later send a MIME header
     66                     if (request.toString().indexOf("HTTP/") != -1) {
     67                         out.write(this.header);
요기!!!
     68                     }
     69
     70                     out.write(this.content);
     71                     out.flush();

[/code]

out.write("\r\n");이 빠진걸지도...
근데 저 클라이언트라면 빠져도 별 상관없을거 같은데요~

----
the smile has left your eyes...

asteroid의 이미지

Server측 HTTP를 제대로 구현하지 않으신 것 같습니다.

작성하신 두 프로그램이 서로 통신한다고 가정하면, InputStream.read()의 값이 -1일 경우는 채널이 닫혔을 때(close, shutdown) 이겠죠.
하지만 클라이언트 프로그램에서는 채널을 닫지않았으므로 아마 그 상태에 계속 머물러있는 것 같습니다.

rain의 이미지

그러고 보니 client에서 close하지 않으면
server의 read에서 계속 기다리게 되겠네요.

그럼 일반적으로 HTTP server는 어떤 식으로 data를 받나요?

서버에서 request header의 \r\n\r\n 이후에
Content-Length만큼만 data를 받고
response하는 것이 맞는 방법인가요?

세상에서 가장 이해하기 힘든 것은 내 자신이 그것을 이해할 수 있다는 것이다.
- 알베르트 아인슈타인 -

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.