'연결'에 해당되는 글 1건

<환경 설정>

// : Express 사용
const express = require('express');
const router = express.Router();

// : 데이터베이스 커넥트
const connectPool = require('../connectPool');

router.post('/', async (require, response) => {

    // :: 받아옴
    const { userName } = require.body;

    // :: 쿼리 생성
    const query = "select * from users where userName = ?";

    // :: 쿼리 적용
    try {
        let[rows, fields] = await connectPool.promise()
        .query(query, [userName]); // :: 적용

		// :: 결과 테스트
        const name = rows[0].userName;
        const email = rows[0].userEmail;
        const time = rows[0].userConnectedTime;
        console.log(`이름 : ${name}, 이메일 : ${email}, 시간 : ${time}`);

        response.json({userData: rows});
    } catch(error) {
        
        response.sendStatus(500);
    }
});

module.exports = router;

<테스트>

  1. 빈 유니티 3D 프로젝트 생성
    • 이름 : LocalTest00
  2. Asset 추가
    • JSON .NET For Unity : JSON 쉽게 쓰기 위한 것
  3. Scene 이름 변경
    • SampleScene ⇒ App
  4. App 오브젝트 및 스크립트 제작
    • 빈 오브젝트 생성 및 이름 변경 : App
    • Scripts 폴더를 만들고 그 안에 App 스크립트 제작
    • App 스크립트를 App 오브젝트에 부착
    • using System.Collections;
      using UnityEngine;
      using UnityEngine.UI;
      using UnityEngine.Networking;
      using Protocols;
      using Newtonsoft.Json;
      using System.Text;
      
      public class App : MonoBehaviour
      {
          // : Objects
          public Button BUTTON_Send;
          public InputField IFIELD_Name;
          public Text TEXT_Output;
      
          // : Status
          const string SERVER_HOST = "http://localhost:";
          const int SERVER_PORT = 3000;
      
          // Start is called before the first frame update
          void Start()
          {
              this.BUTTON_Send.onClick.AddListener(() =>
              {
                  // :: 객체 생성
                  string userName = IFIELD_Name.text;
                  Packets.find_req findRequest = new Packets.find_req(userName);
      
                  // :: 요청
                  this.StartCoroutine(this.RequestFind(findRequest));
              });
          }
      
          // : Request
          // :: IEnumerator 사용 이유 : SendWebRequest를 비동기 전송으로 하려고
          private IEnumerator RequestFind(Packets.find_req packet)
          {
              // :: 직렬화
              string json = JsonConvert.SerializeObject(packet);
      
              // :: 요청객체 생성
              string url = string.Format("{0}{1}", SERVER_HOST + SERVER_PORT, "/find");
              UnityWebRequest webRequest = new UnityWebRequest(url, "POST");
      
              // :: 바디
              var bodyRaw = Encoding.UTF8.GetBytes(json); // :: 한글 처리를 위해 UTF8 설정
      
              // :: 이벤트
              webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw); // :: 이 부분 좀 더 이해 필요
              webRequest.downloadHandler = new DownloadHandlerBuffer(); // :: Response 받아오는 애 : 이해 필요
      
              // :: 헤더 설정
              webRequest.SetRequestHeader("Content-Type", "application/json"); // :: JSON이라고 알려줌
      
              // :: 비동기 전송
              yield return webRequest.SendWebRequest();
      
              // :: 응답 : 에러 처리
              if(webRequest.isNetworkError || webRequest.isHttpError)
              {
                  Debug.Log("www error");
              } else // :: 응답 : 결과 처리
              {
                  Debug.LogFormat("responseCode: {0}", webRequest.responseCode);
      
                  // :: 데이터 받기
                  byte[] resultRaw = webRequest.downloadHandler.data; // :: 왜인지 바이트로 전달함
                  string resultJSON = Encoding.UTF8.GetString(resultRaw); // :: 바이트를 문자열로 변경
                  
                  Debug.Log(resultJSON);
      
                  // :: 역직렬화 ⇒ find_req
                  Packets.find_res result = JsonConvert.DeserializeObject<Packets.find_res>(resultJSON);
      
                  // :: UI 출력
                  string userOutput = "";
                  foreach(Packets.info_userData data in result.userData)
                  {
                      userOutput += string.Format("이름 : {0}\n", data.userName);
                      userOutput += string.Format("이메일 : {0}\n", data.userEmail);
                      userOutput += string.Format("접속 시간 : {0}\n", data.userConnectedTime);
                  }
                  this.SetText_Output(userOutput);
              } 
          }
      
          // : Set
          private void SetText_Output(string text)
          {
              this.TEXT_Output.text = text;
          }
      }
      
  5. Protocols 스크립트 제작
    • Scripts 폴더에 Protocols 스크립트 제작
    • using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      
      namespace Protocols
      {
          public class Packets
          {
              // : 직렬화
              // : 클라이언트 ⇒ 서버
              public class find_req
              {
                  public string userName;
                  public find_req(string userName)
                  {
                      this.userName = userName;
                  }
              }
      
              // : 역직렬화
              // : 서버 ⇒ 클라이언트
              public class find_res
              {
                  public List<info_userData> userData;
              }
      
              // : 역직렬화 대상
              public class info_userData
              {
                  public string userID;
                  public string userName;
                  public string userEmail;
                  public string userPassword;
                  public string userConnectedTime;
              }
          }
      }
  6. 전송 Button 생성
    1. 이름 : Button_Send
  7. 이름을 전송할 Input Field 생성
    1. 이름 : InputField_Name
  8. 정보가 나올 Text 생성
    1. 이름 : Text_Output
  9. Button, Input Field, Text를 App에 연결
  10. 테스트 결과 확인
  • 추가 테스트 : 좀 더 UI
블로그 이미지

RIsN

,