'Server/Study'에 해당되는 글 4건

  1. 2019.07.01 03. Node.js 서버에 연동하여 Image Upload 및 Download하기 1
  2. 2019.07.01 02. 로그인 연동 / api 설계
  3. 2019.06.28 01. 로그인/회원가입
  4. 2019.06.28 01. 참고사이트

03. Node.js 서버에 연동하여 Image Upload 및 Download하기

Server/Study 2019. 7. 1. 15:57



Node.js 웹서버와 연동하여 Image를 Upload하고 Download하는 것을 만들었다.


Upload는 POST 방식으로, Download는 Unity의 UnityWebRequestTexture.GetTexture()를 이용하여 만들었다.


찾아봐도 정보가 별로없고, 제대로 생각을 못해서 그런지 좀 버벅였다.


그래도 열심히 찾아봐서 도움이 많이된 것 같다.


추후에 다시 연습해봐야겠다.



Server

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
const express = require('express');
const mysql = require('mysql');
const multer = require('multer');
const fs = require('fs');
const app = express();
var router = express.Router();
module.exports = router;
 
app.use(express.json());
console.log(__dirname + '/uploads');
app.use(express.static(__dirname + '/uploads'));
 
app.listen(3005, () =>
{
    console.log("서버시작, 3005번 포트");
});
 
let storage = multer.diskStorage({
    destination: function(req, file, callback){
        callback(null"uploads/");
    },
    filename: function(req, file, callback){
        callback(null, file.originalname);
    }
});
 
let upload = multer({
    storage: storage
});
 
app.post('/api/uploadimage', upload.single("imgfile"), (req, res, next) =>
{
    let file = req.file;
 
    console.log("접속함");
 
    res.json({
        success: true,
        imageurl: `http://127.0.0.1:3005/uploads/'${req.filename}'`
    });
});
cs

Client
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
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using Newtonsoft.Json;
 
public class packet
{
    public int errorno;
}
 
public class req_uploadimage
{
    public string name;
}
 
public class res_uploadimage : packet
{
    public bool success;
}
 
public class req_getimage
{
    public string url;
}
 
public class res_getimage : packet
{
    public string imagename;
}
 
public class App : MonoBehaviour
{
    public Sprite sampleImage;
    public Button btnUploadImage;
    public Button btnDownloadImage;
    public Image image;
 
    private string serverPath = "http://127.0.0.1:3005";
    private void Start()
    {
        this.SetBtnsEvent();
    }
 
    private void SetBtnsEvent()
    {
        this.btnUploadImage.onClick.AddListener(() =>
        {
            var reqUploadImage = new req_uploadimage();
            this.sampleImage.name = "imgfile";
            reqUploadImage.name = "imgfile";
            var json = JsonConvert.SerializeObject(reqUploadImage);
 
            StartCoroutine(this.Upload(json, (result) =>
            {
                var responseResult = JsonConvert.DeserializeObject<res_uploadimage>(result);
                Debug.Log("성공여부 : " + responseResult.success);
            }));
        });
 
        this.btnDownloadImage.onClick.AddListener(() =>
        {
            StartCoroutine(this.GetImage("sampleimage.png", (result) =>
            {
                var tex2D = (Texture2D)result;
                var rect = new Rect(00, tex2D.width, tex2D.height);
                this.image.sprite = Sprite.Create(tex2D, rect, new Vector2(0.5f, 0.5f));
 
            }));
        });
    }
 
    private IEnumerator GetImage(string imagename, System.Action<Texture> OnCompleteDownload)
    {
        var path = string.Format("{0}/{1}"this.serverPath, imagename);
        UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(path);
        yield return webRequest.SendWebRequest();
 
        if (webRequest.isNetworkError || webRequest.isHttpError)
        {
            Debug.Log(webRequest.error);
        }
        else
        {
            OnCompleteDownload(((DownloadHandlerTexture)webRequest.downloadHandler).texture);
        }
    }
 
    private IEnumerator Upload(string data, System.Action<string> OnCompleteUpload)
    {
        //이미지 sprite -> texture2d로 변환후 png로 변환
        var img = this.sampleImage;
        var newTex = new Texture2D((int)img.rect.width, (int)img.rect.height);
        var newColors = img.texture.GetPixels((int)img.textureRect.x, (int)img.textureRect.y, (int)img.textureRect.width, (int)img.textureRect.height);
        newTex.SetPixels(newColors);
        newTex.Apply();
        var tex = ImageConversion.EncodeToPNG(newTex);
 
        var byteArr = Encoding.UTF8.GetBytes(data);
        List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
        formData.Add(new MultipartFormFileSection("imgfile", tex, "sampleimage.png""image/png"));
 
        var path = string.Format("{0}/{1}"this.serverPath, "api/uploadimage");
        UnityWebRequest webRequest = UnityWebRequest.Post(path, formData);
        webRequest.downloadHandler = new DownloadHandlerBuffer();
        yield return webRequest.SendWebRequest();
 
        var result = webRequest.downloadHandler.text;
        OnCompleteUpload(result);
    }
}
 
cs


'Server > Study' 카테고리의 다른 글

02. 로그인 연동 / api 설계  (0) 2019.07.01
01. 로그인/회원가입  (0) 2019.06.28
01. 참고사이트  (0) 2019.06.28
:

02. 로그인 연동 / api 설계

Server/Study 2019. 7. 1. 02:38




서버의 db에 uid를 저장하고 어플 시작시 확인 후 미 로그인 시 로그인할 수 있게 만들었다.


근데 gpgs를 연동까지 해놨는데 apk빌드해서 nox에 설치해보니 아무것도 실행이 안된다..


왜이럴까


image를 convert하여 주고 받는 것도 만들긴 했는데, serialize가 안된다.


해결법을 찾아보려 했지만 안돼서 다른 방법을 찾아야 할 것 같다.


더이상 머리가 굴러가지 않아서 쉬어야겠다.



Server

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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
const express = require('express');
const mysql = require('mysql');
const fs = require('fs');
const app = express();
 
//인코딩펑션
function base64_encode(file)
{
    var bitmap = fs.readFileSync(file);
    return new Buffer(bitmap).toString('base64');
}
 
//db접속
const connectDB = (callback) =>
{
    var connection = mysql.createConnection(
        {
            host : '127.0.0.1',
            user : 'root',
            password : '',
            database : 'testServer',
            port : '3306'
        }
    );
 
    connection.connect((err) =>
    {
        if(err)
        {
            console.log(err);
            connection.end();
            throw err;
        }
        else
        {
            console.log("DataBase에 접속하였습니다.");
            callback(connection);
        }
    });
};
 
app.use(express.json()); //json을 사용함
 
//getimage
app.route("/api/getimage").post((req, res) =>
{
    const data = req.body;
 
    connectDB((connection) =>
    {
        var sql = `select * from images where uid = '${data.uid}' and imageid = '${data.imageid}'`;
        console.log(sql);
 
        connection.query(sql, (err, result, fields) =>
        {
            console.log("getimage query 실행됨");
            if(err)
            {
                console.log(err.errorno);
                res.json({
                    cmd : 1301,
                    errorno : err.errorno
                });
            }
            else
            {
                console.log("get image 성공!");
                res.json({
                    cmd : 200,
                    imagebit : result.imagebit
                });
            }
        });
    });
});
 
//uploadimage
app.route("/api/uploadimage").post((req, res) =>
{
    const data = req.body;
 
    connectDB((connection) =>
    {
        var sql = `insert into images(uid, imagebit) values ('${data.uid}''${data.imagebit}')`;
        console.log(sql);
 
        connection.query(sql, (err, result, fields) =>
        {
            console.log("upload image query 실행됨");
            if(err)
            {
                console.log(err.errorno);
                res.json({
                   cmd : 1401,
                   errorno : err.errorno
                });
            }
            else
            {
                console.log("upload image 성공!");
                res.json({
                    cmd : 200
                });
            }
        });
        connection.end();
    });
});
 
//회원가입
app.route("/api/join").post((req, res) =>
{
    const data = req.body;
    console.log("uid in join : " + data.uid);
 
    connectDB((connection) =>
    {
        var sql = `insert into users(uid, androidlogin, androidid, nickname) values
         ('${data.uid}''${data.androidlogin}''${data.androidid}''${data.nickname}')`;
        console.log(sql);
        
        connection.query(sql, (err, result, fields) =>
        {
            console.log("쿼리실행됨");
            if(err)
            {
                //insert중 에러
                console.log(err.errorno);
                res.json({
                    cmd : 1101,
                    errorno : err.errorno
                });
            }
            else
            {
                console.log("성공");
                console.log(result);
                res.json({
                    cmd : 200
                })
            }
            connection.end();
        });
    });
});
 
//로그인
app.route("/api/login").post((req, res) =>
{
    const data = req.body;
    console.log("유저아이디 : " + data.uid);
 
    var uid = data.uid;
    var checkfield = "uid";
 
    if(data.androidlogin == 1)
    {
        uid = data.androidid;
        checkfield = "androidid";
    }
 
    connectDB((connection) =>
    {
        var sql = `select * from users where ${checkfield} = '${uid}'`;
        console.log("쿼리문 : " + sql);
 
        connection.query(sql, (err, results, fields) =>
        {
            if(err)
            {
                //db검색중 에러
                console.log(err);
                res.json({
                    cmd : 1001,
                    errorno : err.errorno
                });
            }
            else
            {
                console.log(results);
                if(results[0=== undefined)
                {
                    //없는 유저
                    res.json({
                        cmd : 1101,
                        errorno : 9001
                    });
                }
                else
                {
                    console.log(results[0].nickname);
                    res.json({
                        cmd : 200,
                        nickname : results[0].nickname
                    });
                }
            }
        });
    });
});
 
app.listen(3005, () =>
{
    console.log("서버시작, 3005번 포트");
});
cs



Client

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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.UI;
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
using UnityEngine.Networking;
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
 
public class packet
{
    public int cmd;
}
 
public class res_join : packet
{
    public int errorno;
}
public class res_login : packet
{
    public int errorno;
    public string nickname;
}
public class res_uploadimage : packet
{
    public int errorno;
}
public class res_getimage : packet
{
    public int errorno;
    public string imagebit;
}
 
public class req_join : packet
{
    public string uid;
    public int androidlogin;
    public string androidid;
    public string nickname;
}
public class req_login : packet
{
    public string uid;
    public int androidlogin;
    public string androidid;
}
public class req_uploadimage : packet
{
    public string uid;
    public string imagebit;
}
public class req_getimage : packet
{
    public string uid;
    public int imageid;
}
 
 
public class App : MonoBehaviour
{
    public Button btnSendImage;
    public Button btnGetImage;
    public Button btnLoginGuest;
    public Button btnLoginGoogle;
    public Text txtNickName;
    public Text txtNull;
    public GameObject welcome;
    public Image image;
    [SerializeField]
    public Sprite exampleImage;
 
    private string serverPath = "http://127.0.0.1:3005";
    private string uid;
    private string androidId;
 
    // Start is called before the first frame update
    void Start()
    {
        this.SetBtnsEvent();
        this.Init();
    }
 
    private void Init()
    {
        this.uid = SystemInfo.deviceUniqueIdentifier;
        this.androidId = PlayGamesPlatform.Instance.localUser.id;
 
        Debug.Log(this.uid);
        Debug.Log(this.androidId.Length);
 
        if (this.androidId == "")
        {
            this.Login((resultLogin) =>
            {
                if (resultLogin == false)
                {
                    this.txtNull.gameObject.SetActive(true);
                    this.btnLoginGoogle.gameObject.SetActive(true);
                    this.btnLoginGuest.gameObject.SetActive(true);
                }
                else
                {
                    this.txtNull.gameObject.SetActive(false);
                    this.welcome.SetActive(true);
                    this.btnLoginGoogle.gameObject.SetActive(false);
                    this.btnLoginGuest.gameObject.SetActive(false);
                    this.btnSendImage.gameObject.SetActive(true);
                    this.btnGetImage.gameObject.SetActive(true);
                }
            });
        }
    }
 
    private void SetBtnsEvent()
    {
        //이미지보내기
        this.btnSendImage.onClick.AddListener(() =>
        {
            //this.UploadImage((result) =>
            //{
 
            //});
        });
 
        //이미지저장
        this.btnGetImage.onClick.AddListener(() =>
        {
 
        });
 
        //게스트로그인
        this.btnLoginGuest.onClick.AddListener(() =>
        {
            this.Join((resultJoin) =>
            {
                if(resultJoin)
                {
                    this.Login((resultLogin) =>
                    {
                        if (resultLogin)
                        {
                            this.txtNull.gameObject.SetActive(false);
                            this.welcome.SetActive(true);
                            this.btnLoginGoogle.gameObject.SetActive(false);
                            this.btnLoginGuest.gameObject.SetActive(false);
                            this.btnSendImage.gameObject.SetActive(true);
                            this.btnGetImage.gameObject.SetActive(true);
                        }
                    });
                }
            });
        });
 
        //구글로그인
        this.btnLoginGoogle.onClick.AddListener(() =>
        {
            Social.localUser.Authenticate((bool success) =>
            {
                if(success)
                {
                    this.Join((resultJoin) =>
                    {
                        this.Login((resultLogin) =>
                        {
                            if (resultLogin)
                            {
                                this.txtNull.gameObject.SetActive(false);
                                this.welcome.SetActive(true);
                                this.btnLoginGoogle.gameObject.SetActive(false);
                                this.btnLoginGuest.gameObject.SetActive(false);
                                this.btnSendImage.gameObject.SetActive(true);
                                this.btnGetImage.gameObject.SetActive(true);
                            }
                        });
                    }
                    , true);
                }
                else
                {
                    Debug.Log("구글 연결실패");
                    this.txtNull.text = "구글 연동에 실패했습니다.";
                }
            });
        });
 
    }
 
    private void GetImgae(Action<bool> OnCompleteGetImage)
    {
        var reqGetImage = new req_getimage();
        reqGetImage.cmd = 1300;
        reqGetImage.uid = this.uid;
        reqGetImage.imageid = 1;
 
        var json = JsonConvert.SerializeObject(reqGetImage);
 
        StartCoroutine(this.Post("api/getimage", json, (result) =>
        {
            var responseResult = JsonConvert.DeserializeObject<res_getimage>(result);
 
            if(responseResult.cmd == 200)
            {
                Debug.Log("get image 성공");
                byte[] imageData = Convert.FromBase64String(responseResult.imagebit);
                var texture = new Texture2D(11, TextureFormat.ARGB32, falsetrue);
                texture.hideFlags = HideFlags.HideAndDontSave;
                texture.filterMode = FilterMode.Point;
                texture.LoadImage(imageData);
 
                var rect = new Rect(00, texture.width, texture.height);
                this.image.sprite = Sprite.Create(texture, rect, new Vector2(0.5f, 0.5f));
                OnCompleteGetImage(true);
            }
            else
            {
                Debug.Log("get 실패");
                Debug.Log(responseResult.errorno);
                OnCompleteGetImage(false);
            }
        }));
    }
 
    private void UploadImage(Action<bool> OnCompleteUpload)
    {
        var reqUploadImage = new req_uploadimage();
        reqUploadImage.cmd = 1400;
        reqUploadImage.uid = this.uid;
        var sprite = this.exampleImage;
        var texture = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height);
        var pixels = sprite.texture.GetPixels((int)sprite.textureRect.x, (int)sprite.textureRect.y
            , (int)sprite.textureRect.width, (int)sprite.textureRect.height);
        texture.SetPixels(pixels);
        texture.Apply();
 
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms, texture);
        var bytes = ms.ToArray();
 
        var data = Convert.ToBase64String(bytes);
 
        StartCoroutine(this.Post("api/uploadimage", data, (result) =>
        {
            var responseResult = JsonConvert.DeserializeObject<res_uploadimage>(result);
            if(responseResult.cmd == 200)
            {
                Debug.Log("upload 성공!");
                OnCompleteUpload(true);
            }
            else
            {
                Debug.Log("업로드실패");
                Debug.Log(responseResult.errorno);
                OnCompleteUpload(false);
            }
        }));
    }
 
    private void Login(Action<bool> OnCompleteLogin, bool androidLogin = false)
    {
        var reqLogin = new req_login();
        reqLogin.cmd = 1100;
        reqLogin.uid = this.uid;
        if (androidLogin)
        {
            reqLogin.androidlogin = 1;
            reqLogin.androidid = PlayGamesPlatform.Instance.localUser.id;
        }
        else
        {
            reqLogin.androidlogin = 0;
        }
 
        var json = JsonConvert.SerializeObject(reqLogin);
 
        StartCoroutine(this.Post("api/login", json, (result) =>
        {
            var responseResult = JsonConvert.DeserializeObject<res_login>(result);
 
            if (responseResult.cmd == 200)
            {
                Debug.Log("로그인성공");
                this.txtNickName.text = responseResult.nickname;
                OnCompleteLogin(true);
            }
            if (responseResult.errorno == 9001)
            {
                Debug.Log("uid가 존재하지 않습니다.");
                OnCompleteLogin(false);
            }
        }));
    }
 
    private void Join(Action<bool> OnCompleteJoin, bool androidLogin = false)
    {
        var reqJoin = new req_join();
        reqJoin.cmd = 1200;
        reqJoin.uid = this.uid;
        reqJoin.nickname = "홍길동";
        if (androidLogin)
        {
            reqJoin.androidlogin = 1;
            reqJoin.androidid = PlayGamesPlatform.Instance.localUser.id;
        }
        else
        {
            reqJoin.androidlogin = 0;
            reqJoin.androidid = "x";
        }
 
        var json = JsonConvert.SerializeObject(reqJoin);
 
        StartCoroutine(this.Post("api/join", json, (result) =>
        {
            var responseResult = JsonConvert.DeserializeObject<res_join>(result);
 
            if (responseResult.cmd == 200)
            {
                Debug.Log("회원가입성공");
                OnCompleteJoin(true);
            }
            if (responseResult.errorno == 1062)
            {
                Debug.Log("중복아이디");
                OnCompleteJoin(false);
            }
        }));
    }
 
    private IEnumerator Post(string uri, string data, Action<string> OnResponse)
    {
        var url = string.Format("{0}/{1}", this.serverPath, uri);
        var req = new UnityWebRequest(url, "POST");
        byte[] body = Encoding.UTF8.GetBytes(data);
 
        req.uploadHandler = new UploadHandlerRaw(body);
        req.downloadHandler = new DownloadHandlerBuffer();
        req.SetRequestHeader("Content-Type""application/json");
 
        yield return req.SendWebRequest();
 
        OnResponse(req.downloadHandler.text);
    }
}
cs


'Server > Study' 카테고리의 다른 글

03. Node.js 서버에 연동하여 Image Upload 및 Download하기  (1) 2019.07.01
01. 로그인/회원가입  (0) 2019.06.28
01. 참고사이트  (0) 2019.06.28
:

01. 로그인/회원가입

Server/Study 2019. 6. 28. 17:54

어제 오늘 Node.js / MySQL / Unity를 이용하여 서버에 회원가입하고 로그인 하는 것을 만들었다.


회원 여부 확인은 Unity의 SystemInfo.deviceUniqueIdentifier를 이용해서 확인했다.


서버에서는 로그인 요청을 받고, DB에서 확인하여 UserID가 있으면 Unity에서 로그인 성공을, DB에 없다면 Unity에서 회원가입 창이 뜨게 했다.




Server

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
const express = require('express');
const mysql = require('mysql');
const app = express();
 
const connectDB = (callback) =>
{
  var con = mysql.createConnection(
    {
      host : '127.0.0.1',
      user : 'root',
      password : '123456',
      database : 'test'
    }
  );
 
  con.connect((err) =>
  {
    if(err){
      console.log(err);
      con.end();
      throw err;
    }
    else{
      console.log("DB접속 성공");
      callback(con);
    }
 
  });
};
 
 
app.use(express.json());
 
 
//로그인
app.route("/api/signin").post((req, res) =>
{
  const data = req.body;
  console.log(data.uid);
 
  connectDB((con) =>
  {
    var sql = `select * from users where uid = '${data.uid}'`;
    console.log(sql);
    con.query(sql, (err, results, fields) =>
    {
      if(err)
      {
        //검색중에 오류가 생겼을 경우
        console.log(err);
        res.json({
          cmd : 1101,
          errorno : err.errno
        });
      }
      else
      {
        console.log(results);
        if(results[0=== undefined)
        {
          //유저가 없음
          res.json({
            cmd : 1101,
            errorno : 9001
          });
        }
        else
        {
          res.json({
            cmd : 200
          });
        }
      }
    });
  });
});
 
//회원가입
app.route("/api/join").post((req, res) =>
{
  const user = req.body;
  console.log(user.uid, user.nickname);
 
  //db접속
  connectDB((con) =>
  {
    var sql = `insert into users(uid, nickname) values ('${user.uid}''${user.nickname}')`;
    console.log(sql);
    con.query(sql, (err, result, fields) =>
    {
      if(err)
      {
        console.log(err.errno);
        res.json(
          {
            cmd : 1001,
            errorno : err.errno
          }
        );
      }
      else
      {
        console.log(result);
        res.json(
        {
          cmd : 200
        });
      }
      con.end();
    });
  });
 
 
});
 
app.listen(3001, () =>
{
  console.log("시작 3001포트");
});
cs



Client

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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO;
using System.Text;
using UnityEngine.Networking;
using Newtonsoft.Json;
 
#region 공통구조체
public class packet
{
    public int cmd;
}
#endregion
 
//로그인 시 응답 객체
public class res_sign : packet
{
    public int errorno;
}
 
//로그인 시 전송하는 객체
public class req_sign : packet
{
    public string uid;
}
 
//회원가입 시 응답 객체
public class res_join : packet
{
    public int errorno;
}
 
//회원가입시 전송하는 객체
public class req_join : packet
{
    public string uid;
    public string nickname;
}
 
public class App : MonoBehaviour
{
    public GameObject signinGo;
    public GameObject joinGo;
    public Text txtUID;
    public Text txtNickName;
    public Text txtSuccessLogin;
    public Button btn;
    public Button btnSubmit; //서버전송
    public InputField inputField;
 
    public Button btnSignin;
    public InputField signinInputField;
 
    private string uid;
 
 
    // Start is called before the first frame update
    void Start()
    {
        //서버에 요청 (device의 uid 등록여부 확인)
 
        this.Init();
 
 
 
        //버튼 이벤트 등록
        this.btn.onClick.AddListener(() =>
        {
            if(string.IsNullOrEmpty (this.inputField.text))
            {
                Debug.Log("닉네임을 입력해주세요.");
            }
            else
            {
                this.txtNickName.text = this.inputField.text;
 
                this.inputField.gameObject.SetActive(false);
                this.btn.gameObject.SetActive(false);
                this.txtNickName.gameObject.SetActive(true);
                this.btnSubmit.gameObject.SetActive(true);
            }
        });
        this.btnSignin.onClick.AddListener(() =>
        {
            Debug.Log("로그인 버튼누름");
            this.SignIn((success) =>
            {
                if(success)
                {
                    this.txtSuccessLogin.gameObject.SetActive(true);
                }
            });
        });
        this.btnSubmit.onClick.AddListener(() =>
        {
            var reqJoin = new req_join();
            reqJoin.cmd = 1000;
            reqJoin.uid = this.txtUID.text;
            reqJoin.nickname = this.txtNickName.text;
 
            var json = JsonConvert.SerializeObject(reqJoin);
            Debug.Log(json);
 
            StartCoroutine(this.Post("api/join", json, (result) =>
            {
                //응답 
                var responseResult = JsonConvert.DeserializeObject<res_join>(result);
                Debug.Log(responseResult);
                if(responseResult.cmd == 200)
                {
                    this.joinGo.SetActive(false);
                    this.signinGo.SetActive(true);
                }
                else
                {
                    if(responseResult.errorno == 1062)
                    {
                        Debug.Log("이미 회원등록되었습니다.");
                    }                    
                }
            }));
 
        });
    }
 
    private void Init()
    {
        this.uid = SystemInfo.deviceUniqueIdentifier;
        this.txtUID.text = this.uid;
        this.btnSubmit.gameObject.SetActive(false);
        this.txtNickName.gameObject.SetActive(false);
        this.SignIn((success) =>
        {
            if(success == false)
            {
                this.joinGo.SetActive(true);
            }
            else
            {
                this.txtSuccessLogin.gameObject.SetActive(true);
            }
        });
    }
 
    private void SignIn(System.Action<bool> OnComplete)
    {
        var reqSignin = new req_sign();
        reqSignin.cmd = 1100;
        reqSignin.uid = this.uid;
        var json = JsonConvert.SerializeObject(reqSignin);
 
        StartCoroutine(this.Post("api/signin", json, (result) =>
        {
            //응답 
            var responseResult = JsonConvert.DeserializeObject<res_sign>(result);
            Debug.Log(responseResult);
            Debug.LogFormat("<color=red>{0}</color>", responseResult.cmd);
 
            if (responseResult.cmd == 200)
            {
                Debug.Log("로그인 성공");
                OnComplete(true);
            }
            if (responseResult.errorno == 9001)
            {
                Debug.Log("회원등록이 되지 않은 아이디입니다.");
                OnComplete(false);
            }
        }));
    }
 
    private string serverPath = "http://127.0.0.1:3001";
 
    private IEnumerator Post(string uri, string data, Action<string> onResponse)
    {
        var url = string.Format("{0}/{1}"this.serverPath, uri);
        Debug.Log(url);
        Debug.Log(data);
 
        var req = new UnityWebRequest(url, "POST");
        byte[] body = Encoding.UTF8.GetBytes(data);
        Debug.Log(body);
 
        req.uploadHandler = new UploadHandlerRaw(body);
        req.downloadHandler = new DownloadHandlerBuffer();
        req.SetRequestHeader("Content-Type""application/json");
 
        yield return req.SendWebRequest();
 
        onResponse(req.downloadHandler.text);
    }
}
 
cs


'Server > Study' 카테고리의 다른 글

03. Node.js 서버에 연동하여 Image Upload 및 Download하기  (1) 2019.07.01
02. 로그인 연동 / api 설계  (0) 2019.07.01
01. 참고사이트  (0) 2019.06.28
:

01. 참고사이트

Server/Study 2019. 6. 28. 11:18

Node.js v10.16.0 Documentation

https://nodejs.org/dist/latest-v10.x/docs/api/


Node.js Guide

https://nodejs.org/ko/docs/guides/


JavaScript Tutorial

https://www.w3schools.com/js/default.asp


SQL Tutorial

https://www.w3schools.com/sql/default.asp


NodeJS를 이용한 API 서버만들기

http://webframeworks.kr/tutorials/nodejs/api-server-by-nodejs-01/


WEB2 - Node.js (생활코딩)

https://opentutorials.org/course/3332

'Server > Study' 카테고리의 다른 글

03. Node.js 서버에 연동하여 Image Upload 및 Download하기  (1) 2019.07.01
02. 로그인 연동 / api 설계  (0) 2019.07.01
01. 로그인/회원가입  (0) 2019.06.28
: