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 |