nodejs restful api server with unity

Unity3D 2019. 1. 4. 13:33
반응형

노드JS , RESTful API 서버 



app.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
console.log('Starting app.js...');
 
const express = require('express');
const app = express();
 
//body 파싱 미들웨어 
app.use(express.json());
 
//라우팅 
app.route('/api/login').post(function(req, res){
    //console.log(req.body);
    console.log(req.body.cmd,req.body.id,req.body.userName);
 
    //DB접속 
    //DB조회 
    var isSuccess = false;
    if( isSuccess){
        //조회 성공 
    }else{
        //조회 실패 
        var res_login = {
            "cmd"901,
            "message""로그인 실패"
        };
        var json = JSON.stringify(res_login);
        res.send(json);
    }
});
 
app.get('/', (req, res)=>{
    console.log('요청받았습니다.');
 
    //응답 
    //res.send('응답했다.!');
    res.json({
        cmd: 200
        message: '안녕하세요?'
    });
});
 
app.listen(3000, ()=>{
    console.log('서버가 시작되었습니다. 포트 : 3000');
});
cs




클라이언트 : 유니티
GET, POST 
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
132
133
134
135
136
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using Newtonsoft.Json;
using System.Text;
 
public class res_common
{
    public int cmd;               //상태코드 
    public string message;        //결과 문자열 
}
 
public class req_common
{
    public int cmd; 
}
 
//요청 
// cmd: 900, id: lim@naver.com, userName: 임꺽정, 
 
//응답 
// 성공: cmd: 200, message: 성공 
// 에러: cmd: 901, message: 문자열 
 
public class req_login : req_common
{
    public string id;
    public string userName;
}
 
public class res_login : res_common { }
 
 
 
 
public class Test : MonoBehaviour
{
    public Button btn;
    public InputField ifId;
    public InputField ifUserName;
 
    private const string serverPath = "http://192.168.0.133:3000";
 
    // Start is called before the first frame update
    void Start()
    {
        btn.onClick.AddListener(() => {
            //http 서버에 요청을 보냄 
            //StartCoroutine(this.Get());
            Debug.LogFormat("{0} {1}", ifId.text, ifUserName.text);
            var req_login = new req_login();
            req_login.cmd = 900;
            req_login.id = ifId.text;
            req_login.userName = ifUserName.text;
            var json = JsonConvert.SerializeObject(req_login);
            StartCoroutine(this.Post("api/login", json));
 
        });
 
        Debug.Log("Hello World");
    }
 
    private IEnumerator Post(string uri, string data)
    {
        var url = string.Format("{0}/{1}", serverPath, uri);
        Debug.Log(url);
        Debug.Log(data);
        //POST방식으로 http서버에 요청을 보내겠습니다.
        var request = new UnityWebRequest(url, "POST");
        byte[] bodyRaw = Encoding.UTF8.GetBytes(data);
        Debug.Log(bodyRaw.Length);
        request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type""application/json");
 
        //응답을 기다립니다.
        yield return request.SendWebRequest();
 
        //응답을 받았습니다.
        //Debug.Log(request.downloadHandler.data);
        Debug.Log(request.downloadHandler.text);
        var res_login = JsonConvert.DeserializeObject<res_login>(request.downloadHandler.text);
        Debug.LogFormat("{0}, {1}", res_login.cmd, res_login.message);
 
    }
 
    #region Get
    private IEnumerator Get(string uri = "")
    {
        //http서버에 요청 
        var url = string.Format("{0}/{1}", serverPath, uri);
        Debug.Log(url);
 
        using (UnityWebRequest www = UnityWebRequest.Get(url))
        {
            //http서버로 부터 응답을 대기 
            yield return www.SendWebRequest();
 
            //http서버로부터 응답을 받았다. 
            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
            }
            else
            {
                //결과를 문자열로 출력 
                Debug.Log(www.downloadHandler.text);
 
                //바이너리 데이터를 복구 
                byte[] results = www.downloadHandler.data;
 
                Debug.Log(results.Length);  //14 
 
                var message = Encoding.UTF8.GetString(results);
 
                Debug.Log(message);     //응답했다.!
 
                var res_common = JsonConvert.DeserializeObject<res_common>(message);
 
                Debug.LogFormat("{0}, {1}", res_common.cmd, res_common.message);
 
            }
        }
 
    }
    #endregion
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
cs




반응형

'Unity3D' 카테고리의 다른 글

Unity UI에 관한 최고의 최적화 팁  (0) 2019.01.15
유니티 Webview 카카로 로그인  (0) 2019.01.14
nodejs restful api unity  (0) 2018.12.31
Unity에서 .NET 4.x 사용  (0) 2018.12.27
socket.io with unity  (1) 2018.12.24
: