UnityWebRequest : 유저 랭킹 정보 가져오기

2021. 7. 27. 13:22unity

 

const express = require("express");
const app = express();

let users =[];
app.use(express.json());


app.get("/",(req,res)=>
{
    res.send('hello express');
});

app.post('/score',(req,res)=>{
    //id,score body 에 받기
    const {id, score}=req.body;
    users[id] = score;
    console.log(users);
    res.status(200).send();
});


app.listen(3030, ()=>
{
    console.log('server is running at port 3030...');
});

간단한 서버 구축

 

const express = require("express");
const app = express();

let users =[];
app.use(express.json());


app.get("/",(req,res)=>
{
    res.send('hello express');
});

app.post('/score',(req,res)=>{
    //id,score body 에 받기
    const {id, score}=req.body;
    
    let result = {
        cmd: -1,
        message: ''
    }

    let user = users.find(x=>x.id == id);

    if(user === undefined){
        //아직 등록이 한번도 안된 유저
        users.push({ id, score });
        result.cmd = 1001;
        result.message = "점수가 신규 등록 되었습니다.";
    }
    else{

        if(score>user.score){
            //등록하려고 하는 점수가 저장된 점수보다 크다면 갱신
            user.score = score;
            result.cmd = 1002;
            result.message = "점수가 갱신되었습니다.";
        }
        else{
            result.cmd = 1003;
            res.status(200).send(result);
        }
    }
    console.log(users);
    res.status(200).send(result);
});


app.listen(3030, ()=>
{
    console.log('server is running at port 3030...');
});

 


랭킹 top3 표시하기

const express = require("express");
const app = express();

let users =[];
app.use(express.json());


app.get("/",(req,res)=>
{
    res.send('hello express');
});

app.post('/score',(req,res)=>{
    //id,score body 에 받기
    const {id, score}=req.body;
    
    let result = {
        cmd: -1,
        message: ''
    }

    let user = users.find(x=>x.id == id);

    if(user === undefined){
        //아직 등록이 한번도 안된 유저
        users.push({ id, score });
        result.cmd = 1001;
        result.message = "점수가 신규 등록 되었습니다.";
    }
    else{

        if(score>user.score){
            //등록하려고 하는 점수가 저장된 점수보다 크다면 갱신
            user.score = score;
            result.cmd = 1002;
            result.message = "점수가 갱신되었습니다.";
        }
        else{
            result.cmd = 1003;
            res.status(200).send(result);
        }
    }
    console.log(users);
    res.status(200).send(result);
});

app.get('/scores/top3',(req,res)=>{
    let result = users.sort(function(a,b){
        return b.score - a.score;
    });

    result = result.slice(0,3);
    
    res.send({
        cmd: 1101,
        message: '',
        result
    })
})


app.listen(3030, ()=>
{
    console.log('server is running at port 3030...');
});

{
    "cmd": 1101,
    "message": "",
    "result": [
        {
            "id": "cho@gmail.com",
            "score": 580
        },
        {
            "id": "hong@gmail.com",
            "score": 500
        },
        {
            "id": "jang@gmail.com",
            "score": 280
        }
    ]
}

유저 검색하기

app.get('/scores/:id',(req,res)=>{
    console.log('id:' + req.params.id);
    let user = users.find(x=>x.id == req.params.id);
    if(user === undefined){
        res.send({
            cmd: 1102,
            message: '잘못된 id 입니다.',
        });
    }
    else{
        res.send({
            cmd: 1103,
            message: '',
            result: user
        });

    }
})


스크립터블 오브젝트 사용하기

https://docs.unity3d.com/kr/2019.4/Manual/class-ScriptableObject.html

 

ScriptableObject - Unity 매뉴얼

ScriptableObject는 클래스 인스턴스와는 별도로 대량의 데이터를 저장하는 데 사용할 수 있는 데이터 컨테이너입니다. ScriptableObject의 주요 사용 사례 중 하나는 값의 사본이 생성되는 것을 방지하

docs.unity3d.com

using UnityEngine;

[CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/SpawnManagerScriptableObject", order = 1)]
public class SpawnManagerScriptableObject : ScriptableObject
{
    public string id;
    public int score;
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json;

public class RankMain : MonoBehaviour
{
    public Button btnGetTop3;
    public Button btnPost;
    public Button btnGet;
    public string host;
    public int port;
    public string top3Uri;
    public string idUri;
    public string postUri;
    public SpawnManagerScriptableObject scriptableObject;


    void Start()
    {
        this.btnGetTop3.onClick.AddListener(() =>
        {
            var url = string.Format("{0}: {1}/{2}", this.host, this.port, this.top3Uri);
            Debug.Log(url);
        });


        this.btnPost.onClick.AddListener(() =>
        {
            var url = string.Format("{0}: {1}/{2}", this.host, this.port, this.postUri);
            Debug.Log(url);

            var req = new Protocols.Packets.req_scores();
            req.cmd = (int)Protocols.eType.POST_SCORE;
            req.id = scriptableObject.id;
            req.score = scriptableObject.score;

            var json = JsonConvert.SerializeObject(req);
            Debug.Log(json);
        });


        this.btnGet.onClick.AddListener(() =>
        {
            var url = string.Format("{0}: {1}/{2}", this.host, this.port, this.idUri);
            Debug.Log(url);
        });
    }

    
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Protocols 
{
    public enum eType
    {
        POST_SCORE =1000,
    }
    public class Packets
    {
        public class common
        {
            public int cmd;
        }

        public class req_scores : common
        {            
            public string id;
            public int score;
        }

        public class res_scores : common
        {
            public string message;            
        }

        public class user
        {
            public string id;
            public int score;
        }

        public class res_scores_top3 : res_scores
        {
            public user[] result;
        }

        public class res_scores_id : res_scores
        {
            public user result;
        }
    }
}

 


GET,POST로 데이터 불러오기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json;
using UnityEngine.Networking;
using System.Text;

public class RankMain : MonoBehaviour
{
    public string host;
    public int port;
    public string top3Uri;
    public string idUri;
    public string postUri;

    public SpawnManagerScriptableObject scriptableObject;

    public Button btnGetTop3;
    public Button btnGetId;
    public Button btnPost;

    void Start()
    {
        this.btnGetTop3.onClick.AddListener(() => {
            var url = string.Format("{0}:{1}/{2}", host, port, top3Uri);
            Debug.Log(url);

            StartCoroutine(this.GetTop3(url, (raw) =>
            {
                var res = JsonConvert.DeserializeObject<Protocols.Packets.res_scores_top3>(raw);
                Debug.LogFormat("{0}, {1}", res.cmd, res.result.Length);
                foreach (var user in res.result)
                {
                    Debug.LogFormat("{0} : {1}", user.id, user.score);
                }
            }));


        });
        this.btnGetId.onClick.AddListener(() => {
            var url = string.Format("{0}:{1}/{2}", host, port, idUri);
            Debug.Log(url);

            StartCoroutine(this.GetId(url, (raw) => {

                var res = JsonConvert.DeserializeObject<Protocols.Packets.res_scores_id>(raw);
                Debug.LogFormat("{0}, {1}", res.result.id, res.result.score);

            }));
        });
        this.btnPost.onClick.AddListener(() => {
            var url = string.Format("{0}:{1}/{2}", host, port, postUri);
            Debug.Log(url); //http://localhost:3030/scores

            var req = new Protocols.Packets.req_scores();
            req.cmd = 1000; //(int)Protocols.eType.POST_SCORE;
            req.id = scriptableObject.id;
            req.score = scriptableObject.score;
            //직렬화  (오브젝트 -> 문자열)
            var json = JsonConvert.SerializeObject(req);
            Debug.Log(json);
            //{"id":"hong@nate.com","score":100,"cmd":1000}

            StartCoroutine(this.PostScore(url, json, (raw) => {
                Protocols.Packets.res_scores res = JsonConvert.DeserializeObject<Protocols.Packets.res_scores>(raw);
                Debug.LogFormat("{0}, {1}", res.cmd, res.message);
            }));

        });
    }

    private IEnumerator GetTop3(string url, System.Action<string> callback)
    {

        var webRequest = UnityWebRequest.Get(url);
        yield return webRequest.SendWebRequest();
        if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.Log("네트워크 환경이 안좋아서 통신을 할수 없습니다.");
        }
        else
        {
            callback(webRequest.downloadHandler.text);
        }
    }

    private IEnumerator GetId(string url, System.Action<string> callback)
    {
        var webRequest = UnityWebRequest.Get(url);
        yield return webRequest.SendWebRequest();

        Debug.Log("--->" + webRequest.downloadHandler.text);

        if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.Log("네트워크 환경이 안좋아서 통신을 할수 없습니다.");
        }
        else
        {
            callback(webRequest.downloadHandler.text);
        }
    }

    private IEnumerator PostScore(string url, string json, System.Action<string> callback)
    {

        var webRequest = new UnityWebRequest(url, "POST");
        var bodyRaw = Encoding.UTF8.GetBytes(json); //직렬화 (문자열 -> 바이트 배열)

        webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
        webRequest.downloadHandler = new DownloadHandlerBuffer();
        webRequest.SetRequestHeader("Content-Type", "application/json");

        yield return webRequest.SendWebRequest();

        if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.Log("네트워크 환경이 안좋아서 통신을 할수 없습니다.");
        }
        else
        {
            Debug.LogFormat("{0}\n{1}\n{2}", webRequest.responseCode, webRequest.downloadHandler.data, webRequest.downloadHandler.text);
            callback(webRequest.downloadHandler.text);
        }
    }

}

GET: scores/top3

 

Get: scores/id

 

Post: /scores