본문

[2017.10.28] 09. Node.js서버와 Android클라이언트 [데이터 통신 DB O with JSON]

도입

이번 포스팅에서는 지난 포스팅에서의 일반 데이터 전달을 JSON 형태의 데이터 전달로 변경해 실습할 예정이다.

(JSON 사용 이유 - http://heepie.tistory.com/174)


Node.js서버와 Android클라이언트 [데이터 통신 DB O with JSON]의  데이터의 흐름


실습

Server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// 1. 라이브러리 가져오기
var http = require("http");
var u = require("url");
var qs = require("querystring");
 
// mongo DB 사용을 위한 라이브러리
var mongo = require("mongodb").MongoClient;
 
// File Stream: 파일을 열기 위한 라이브러리
var fs = require("fs");
 
// 2. 서버 생성
var server = http.createServer(function(request, response) {
  // 주소를 제외한 url 추출
  // console.log(request.url);
  var url = request.url;
 
  var strucedUrl = u.parse(url);
 
  var path = strucedUrl.pathname;
  var cmds = path.split("/");
 
  // console.log(cmds[1]);
  // console.log("Create Server OK");
 
  // RESTFul의 'html' 이라면
  if (cmds[1== "html") {
    console.log("Html OK");
    if (request.method == "GET") {
      console.log("OK");
 
      // '/' 문자 제거
      var filePath = path.substring(1);
      console.log(path);
 
      // 파일을 연다.
      fs.readFile(filePath, 'utf-8',function(error, data){
              if(error){
          // 파일이 없다면 오류 메시지로 응답
                  response.writeHead(404,{'Content-Type':'text/html'});
                  response.end("<h1>404 Page not found!</h1>");
              }else{
          // 파일이 존재하면 해당 파일로 응답
                  response.writeHead(200,{'Content-Type':'text/html'});
                  response.end(data);
              }
          });
    }
  } else if (cmds[1== "signin") {
 
        // GET Method 처리
        if (request.method == "GET") {
            console.log(" ");
            console.log("[GET]");
          mongo.connect("mongodb://localhost:27017/serverdb"function(error, db) {
            if (error) {
              response.write(error);
              response.end("");
            } else {
              var datas = qs.parse(strucedUrl.query);
              console.log(datas);
              var cursor = db.collection("user").find();
              // var itemArray = cursor.toArray();
 
              // console.log(itemArray.length);
 
              // 데이터를 저장할 객체 선언
 
 
              var jsonData = "";
              // dataset에 변환된 item들이 들어간다.
              cursor.toArray(function(err, dataset) {
                if (err) {
 
                } else {
                    console.log(dataset);
                    var item = {
                        code : "OK",
                        data : dataset
                    }
                    // 해당 데이터를 Json 형식으로 변환 
                    response.end(JSON.stringify(item));
 
                }
              });
            //   console.log(" ");
 
            //   response.end("GET OK");
            }
          });
      } else if (request.method == "POST"){
          console.log(" ");
          console.log("[POST]");
          var postdata = "";
          request.on("data"function(fragment) {
              postdata += fragment;
          });
 
          request.on("end"function() {
              mongo.connect("mongodb://localhost:27017/serverdb"function(error, db) {
                  if (error) {
                      response.end(error);
                  } else {
                      var datas = qs.parse(postdata);
                      var cursor = db.collection("user").find(datas);
 
                      cursor.toArray(function(err, dataset) {
                          for (var i=0; i<dataset.length; i=i+1) {
                            // 각각 데이터를 item으로 변환
                            item = dataset[i];
 
                            // 해당 데이터 출력
                            console.log("\t- id -");
                            console.log("\t"+item.id);
                            console.log("\t- pw -");
                            console.log("\t"+item.pw);
                          }
                      });
                      console.log(" ");
                      response.end("POST OK");
                  }
              });
          });
      }
  }
});
 
// 3. 클라이언트 대기
server.listen(9000function() {
  console.log("Server listening ...");
});
cs



Android에서는 Gson 라이브러리를 사용했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class MainActivity extends AppCompatActivity {
    // ...
    private void load() {
        new AsyncTask<Void, Void, Result>() {
 
            @Override
            protected Result doInBackground(Void... voids) {
                String result 
                    = Remote.sendDataGetMethod
                      ("http://192.168.0.139:9001/signin?is=heepie&pw=123456789");
                Log.i("heepie", result);
                Gson gson = new Gson();
                Result data = gson.fromJson(result, Result.class);
                return data;
            }
 
            @Override
            protected void onPostExecute(Result result) {
                Log.i("heepie", result.getMsg());
                setList(result);
 
            }
        }.execute();
    }
    // ...
}
cs

공유

댓글