unity - Server Communication 서버 통신 Json 기반

통신 구조

DataManager Send -> WebManager -> HttpManager

HttpManager -> WebManager Request


DataManager
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class datamanager : MonoBehaviour {
    public WebManager m_sc_WebManager = null;
    public GameObject m_obj_skipbtn = null;
    //public bool EndCheck = false; 
    
    public string Psitnid = null;
    public string Eqpmnid = null;
    public string Detailjobid = null;
    public string Jobid = null;
    // Use this for initialization
    void Start()
    {
        // StartCoroutine(data());
         // StartCoroutine(testRoomMake());
        // StartCoroutine(testRoomJoin());
        // StartCoroutine(testRoomList());
    }
    // Update is called once per frame
    void Update () {
        
    }
    IEnumerator data()
    {
        yield return new WaitForSeconds(2f);
        IDictionary<stringstring> _dataBegin = new Dictionary<stringstring>();
        _dataBegin.Add("PSITNID", Psitnid);
        _dataBegin.Add("EQPMNID", Eqpmnid);
        _dataBegin.Add("DETAILJOBID", Detailjobid);
        _dataBegin.Add("JOBID", Jobid);
        m_sc_WebManager.SendHttpCommand(WebManager.protocol_Begin, _dataBegin);
        if (m_obj_skipbtn)
        {
            m_obj_skipbtn.SetActive(true);
        }
    }
    IEnumerator testRoomMake()
    {
        yield return new WaitForSeconds(3f);
        //Dictionary<string, string> _dataLogin = new Dictionary<string, string>();
        //_dataLogin.Add("id", "test4724");
        //_dataLogin.Add("passwd", "k3ik3ik3i");
        //m_sc_WebManager.SendHttpCommand(WebManager.protocol_Login, _dataLogin);
        IDictionary<stringstring> _dataBegin = new Dictionary<stringstring>();
        _dataBegin.Add("mapType""9");
        _dataBegin.Add("playerId""test001");
        m_sc_WebManager.SendHttpCommand(WebManager.protocol_RoomMake, _dataBegin);
        IDictionary<stringstring> test01 = new Dictionary<stringstring>();
        test01.Add("mapType""9");
        test01.Add("playerId""test002");
        m_sc_WebManager.SendHttpCommand(WebManager.protocol_RoomMake, test01);
        IDictionary<stringstring> test02 = new Dictionary<stringstring>();
        test02.Add("mapType""10");
        test02.Add("playerId""test003");
        m_sc_WebManager.SendHttpCommand(WebManager.protocol_RoomMake, test02);
        IDictionary<stringstring> test03 = new Dictionary<stringstring>();
        test03.Add("mapType""10");
        test03.Add("playerId""test004");
        m_sc_WebManager.SendHttpCommand(WebManager.protocol_RoomMake, test03);
    }
    IEnumerator testRoomJoin()
    {
        yield return new WaitForSeconds(2f);
        //Dictionary<string, string> _dataLogin = new Dictionary<string, string>();
        //_dataLogin.Add("id", "test4724");
        //_dataLogin.Add("passwd", "k3ik3ik3i");
        //m_sc_WebManager.SendHttpCommand(WebManager.protocol_Login, _dataLogin);
        IDictionary<stringstring> _dataRoomJoin = new Dictionary<stringstring>();
        _dataRoomJoin.Add("roomId"1.ToString());
        _dataRoomJoin.Add("playerId""test006");
        m_sc_WebManager.SendHttpCommand(WebManager.protocol_RoomJoin, _dataRoomJoin);
    }
    IEnumerator testRoomList()
    {
        yield return new WaitForSeconds(3f);
        IDictionary<stringstring> _dataBegin = new Dictionary<stringstring>();
        m_sc_WebManager.SendHttpCommand(WebManager.protocol_RoomList, _dataBegin);
    }
    
}
cs

WebManager

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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System;
using SimpleJSON;
using UnityEngine.SceneManagement;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
public class WebManager : MonoBehaviour {
    // ==============================================================================================================
    // Scripts
    // ==============================================================================================================
    // ==============================================================================================================
    // Protocol List
    // ==============================================================================================================
    //http://{serverName}/api/version/check.do
    public const int protocol_version = 10000;
    public const int protocol_Begin = 20000;
    public const int protocol_End = 20001;
    // public const int protocol_End = 10001;
    public const int protocol_Login = 20002;
    public const int protocol_CreateAccount = 20003;
    public const int protocol_IDExist = 20004;
    public const int protocol_Upload = 20005;
    public const int protocol_IndividualRank = 20006;
    public const int protocol_RoomMake = 20007;
    public const int protocol_RoomOut = 20008;
    public const int protocol_RoomList = 20009;
    public const int protocol_RoomInfo = 20010;
    public const int protocol_RoomJoin = 20011;
    public const int protocol_GameStart = 20012;
    public const int protocol_GameEnd = 20013;
    // ==============================================================================================================
    // WEB DEFINE
    // ==============================================================================================================
    public const string WEB_SERVER_Begin = "http://211.194.140.79:9201/api/account/login.do";
    public const string WEB_SERVER_End = "http://211.194.140.79:9201/setEndOfMainenance.do";
    public const string WEB_SERVER_Login = "http://211.194.140.79:9201/api/account/login.do";
    public const string WEB_SERVER_CreateAccount = "http://211.194.140.79:9201/api/account/create.do";
    public const string WEB_SERVER_IDExist = "http://211.194.140.79:9201/api/account/check/id.do";
    public const string WEB_SERVER_Upload = "http://211.194.140.79:9201/api/single/end.do";
    public const string WEB_SERVER_IndividualRank = "http://211.194.140.79:9201/api/rank/update/single.do";
    public const string WEB_SERVER_RoomMake = "http://211.194.140.79:9201/api/multi/create.do";
    public const string WEB_SERVER_RoomOut = "http://211.194.140.79:9201/api/multi/leave.do";
    public const string WEB_SERVER_RoomList = "http://211.194.140.79:9201/api/multi/list.do";
    public const string WEB_SERVER_RoomInfo = "http://211.194.140.79:9201/api/multi/room.do";
    public const string WEB_SERVER_RoomJoin = "http://211.194.140.79:9201/api/multi/join.do";
    public const string WEB_SERVER_GameStart = "http://211.194.140.79:9201/api/multi/start.do";
    public const string WEB_SERVER_GameEnd = "http://211.194.140.79:9201/api/multi/end.do";
    public const string WEB_SERVER_VERSION = "http://211.194.140.79:9201/api/version/check.do";
    //public const string WEB_SERVER_Begin = "http://172.16.1.41:48090/setBeginOfMainenance.do";
    //public const string WEB_SERVER_End = "http://172.16.1.41:48090/setEndOfMainenance.do";
    //public const string WEB_SERVER_End = "http://172.16.1.41:48090/getDailyPerformanceCheckList.do";
    #region variable
    private int m_nWebParsingIndex = 1;
    #endregion
    #region Web manager
    // ==============================================================================================================
    // Web Manager
    // ==============================================================================================================
    HttpManager m_httpManager = null;
    // ==============================================================================================================
    #endregion
    // Use this for initialization
    void Start () {
        Init();
        StartCoroutine(CallWebData());
        //DontDestroyOnLoad(gameObject);
    }
    void Init() {
    }
    IEnumerator CallWebData () {
        yield return new WaitForSeconds(1f);
        m_httpManager = HttpManager.Instance;
        m_httpManager.OnHttpRequest += OnHttpRequest;
        //DontDestroyOnLoad(m_httpManager);
        //SendHttpCommand(protocol_GPS_ARpoint);        
    }    
    public HttpManager GetHttpManager () {
        return m_httpManager;
    }
    void OnGUI() {
        //공지팝업을 노출합니다.
        /*
        if(GUI.Button (new Rect(100,100,200,200), "showPopupNoti")) {
            IgaworksUnityPluginAOS.LiveOps.showigaworkPopUp("??");
        }*/
    }
    void OnApplicationPause(bool pauseStatus){
        
    }
    void InitIGAWorks ( string _sequence ){
        
    }
    
    // ==============================================================================================================
    // OnHttpSend 
    // ==============================================================================================================
    #region HttpSend
    public void SendHttpCommand(int webCmd)
    {
        GetWebPage(webCmd);
    }
    public void SendHttpCommand(int webCmd, IDictionary<stringstring> _data)
    {
        GetWebPage(webCmd, _data);
    }
    public void SendHttpCommand(int webCmd, IDictionary<stringint> _data)
    {
        GetWebPage(webCmd, _data);
    } 
    
    public void GetWebPage(int _nWebCmd) {
        Debug.Log("########## WEB GetWebPage START  INT: " +_nWebCmd);
        //url = DEFAULT_URL + webCmd + "&tel=" + GetCarrier() + "&mdn=" + phoneNumber;
        //string url = DEFAULT_URL + "&cmd" + webCmd.ToString() + "&nt_cd=" + GDefine.g_NATION_CODE.ToString() + "&mk_cd=" + GDefine.g_MARKET_CODE.ToString() + "&gm_ver=" + GDefine.g_VER + "&acc_uuid=" + GDefine.g_UUID   + "&test_mode=" + GDefine.g_GAME_MODE.ToString()  ;
        switch (_nWebCmd)
        {            
            case protocol_Begin:
                
                break;           
            default:
                break;
        }
        Debug.Log("########## WEB GetWebPage END  INT: " + _nWebCmd);
    }
    
    public void GetWebPage(int _nWebCmd, IDictionary<stringstring> _data)
    {
        Debug.Log("########## WEB GetWebPage START  INT: " + _nWebCmd);
        switch (_nWebCmd)
        {
            case protocol_version:
                OnHttpSend(_nWebCmd, WEB_SERVER_VERSION, _data);
                break;
            case protocol_Begin:
                OnHttpSend(_nWebCmd,WEB_SERVER_Begin, _data);
                break;
            case protocol_End:
                OnHttpSend(_nWebCmd,WEB_SERVER_End, _data);
                break;
            case protocol_Login:
                OnHttpSend(_nWebCmd,WEB_SERVER_Login, _data);
                break;
            case protocol_CreateAccount:
                OnHttpSend(_nWebCmd,WEB_SERVER_CreateAccount, _data);
                break;
            case protocol_IDExist:
                OnHttpSend(_nWebCmd,WEB_SERVER_IDExist, _data);
                break;
            case protocol_Upload:
                OnHttpSend(_nWebCmd, WEB_SERVER_Upload, _data);
                break;
            case protocol_IndividualRank:
                OnHttpSend(_nWebCmd, WEB_SERVER_IndividualRank, _data);
                break;
            case protocol_RoomMake:
                OnHttpSend(_nWebCmd, WEB_SERVER_RoomMake, _data);
                break;
            case protocol_RoomOut:
                OnHttpSend(_nWebCmd, WEB_SERVER_RoomOut, _data);
                break;
            case protocol_RoomList:
                OnHttpSend(_nWebCmd, WEB_SERVER_RoomList, _data);
                break;
            case protocol_RoomInfo:
                OnHttpSend(_nWebCmd, WEB_SERVER_RoomInfo, _data);
                break;
            case protocol_RoomJoin:
                OnHttpSend(_nWebCmd, WEB_SERVER_RoomJoin, _data);
                break;
            case protocol_GameStart:
                OnHttpSend(_nWebCmd, WEB_SERVER_GameStart, _data);
                break;
            case protocol_GameEnd:
                OnHttpSend(_nWebCmd, WEB_SERVER_GameEnd, _data);
                break;
            default:
                break;
        }
        Debug.Log("########## WEB GetWebPage END  INT: " + _nWebCmd);
        //public void GetWebPage(int _nWebCmd, st) {
    }
    public void GetWebPage(int _nWebCmd, IDictionary<string,int> _data)
    {
        Debug.Log("########## WEB GetWebPage START  INT: " + _nWebCmd);
        switch (_nWebCmd)
        {
            case protocol_Begin:
                
                break;
            case protocol_End:
               
                break;
            default:
                break;
        }
        Debug.Log("########## WEB GetWebPage END  INT: " + _nWebCmd);
        //public void GetWebPage(int _nWebCmd, st) {
    }
    
    #endregion
    #region Send
    // ==============================================================================================================
    // Send 
    // ==============================================================================================================
   
    public void SetWebProtocol(string _strURL, JSONNode _data)
    {
        OnHttpSend(_strURL, _data);
    }
    public void SetWebProtocol(string _strURL, IDictionary<stringstring> _data)
    {
        OnHttpSend(_strURL, _data);
    }
    public void SetWebProtocol(string _strURL, IDictionary<stringint> _data)
    {
        OnHttpSend(_strURL, _data);
    }
    public JSONNode GetJSONNode(int _nCmd)
    {
        JSONNode postData = null;//JSON.Parse("[]");
        try
        {
            postData = JSON.Parse("{\"code\":0}");
            //postData["cmd"].AsInt = _nCmd;            
        }
        catch
        {
            Debug.LogError("error!!!!");
        }
        return postData;
    }
    
    
    #endregion
    #region HttpSend
    // ==============================================================================================================
    // OnHttpSend 
    // ==============================================================================================================      
    void OnHttpSend(string _url, JSONNode _data) {
        Debug.LogWarning("OnHttpSend");        
        m_httpManager.POST (100, _url, _data);        
    }
    void OnHttpSend(string _url, IDictionary<stringstring> _data)
    {
        Debug.LogWarning("OnHttpSend post");
        m_httpManager.post(100, _url, _data);
    }
    void OnHttpSend(string _url, IDictionary<stringint> _data)
    {
        Debug.LogWarning("OnHttpSend post");
        m_httpManager.post(100, _url, _data);
    }
    // ## 추가
    void OnHttpSend(int _nWebCmd, string _url, IDictionary<stringstring> _data)
    {
        Debug.LogWarning("OnHttpSend post");
        m_httpManager.post(_nWebCmd, _url, _data);
    }
    // Get type
    void OnHttpSend(int nCmd, string _url)
    {
       // string url = WEB_SERVER + "kind = " + _url;
        Debug.Log("_url : " + _url);
       // m_httpManager.get(nCmd, WEB_SERVER_Begin + _url);
    }
    #endregion
    #region OnHttpRequest
    // ==============================================================================================================
    // OnHttpRequest 
    // ==============================================================================================================
    void OnHttpRequest(int id, WWW www) {
        //JSONNode jsonDataS = null;
        //string stringValue = www.text;
        //Debug.Log(stringValue);
        if (www.error != null) {
            Debug.Log ("[Error] " + www.error);
        } else {
            Debug.Log("id : " +id);
            switch (id) {
            case 100:
                    // test code
                    ReceiveWebjsonProcess(id, www);
                break;
//                case protocol_RoomList:
//                    try
//                    {
//                        jsonDataS = JSON.Parse(stringValue);
//                    }
//                    catch
//                    {
//                        jsonDataS = null;
//#if UNITY_EDITOR
//                        Debug.LogError("json parse fail");
//#endif
//                    }
//                    ReceiveDataToJSon(id, jsonDataS);
                    
//                    break;
            default:
                    ReceiveWebjsonProcess(id, www);
                    break;
            }
        }
    }
    // ==============================================================================================================
    // OnHttp Receive 
    // ==============================================================================================================
    public void ReceiveWebjsonProcess(int id, WWW www) {
        
        JSONNode jsonDataS = null;
        string stringValue = www.text;
#if UNITY_EDITOR
        Debug.Log("==============================================================================================================");
        Debug.Log("stringValue : " + stringValue);
#endif
        // ## 추가
        switch (id)  // ## id = cmd 인듯.
        {
            case protocol_Begin:
                //string Beginresult = _data["RESULT"].Value;
                //string Beginmessage = _data["MESSAGE"].Value;
                //string Beginexchistid = _data["EXCHISTID"].Value;
                //Debug.LogError("RESULT: " + Beginresult);
                //Debug.LogError("MESSAGE: " + Beginmessage);
                //Debug.LogError("EXCHISTID: " + Beginexchistid);
                //PlayerPrefs.SetString("EXCHISTID", Beginexchistid);
                //string EXCHISTID = Beginexchistid;
                break;
            case protocol_End:
                //string Endresult = _data["RESULT"].Value;
                //string Endmessage = _data["MESSAGE"].Value;
                //string Endexchistid = _data["EXCHISTID"].Value;
                //Debug.LogError("RESULT: " + Endresult);
                //Debug.LogError("MESSAGE: " + Endmessage);
                //Debug.LogError("EXCHISTID: " + Endexchistid);
                break;
            case protocol_version:
                string strVersion = stringValue;
                GameObject.Find("LoginManager").GetComponent<LogManager>().ReceiveVersion(strVersion); // version
                break;
            case protocol_Login:
                Debug.LogWarning("protocol_Login");
                string loginResult = stringValue;
                GameObject.Find("LoginManager").GetComponent<LogManager>().ReceiveLogin(int.Parse(loginResult)); // 로그인
                break;
            case protocol_CreateAccount:
                Debug.LogWarning("protocol_CreateAccount");
                string CreateAccountResult = stringValue;
                GameObject.Find("LoginManager").GetComponent<LogManager>().ReceiveCreateAccount(int.Parse(CreateAccountResult)); // 계정생성
                break;
            case protocol_IDExist:
                Debug.LogWarning("protocol_IDExist");
                string IDExistResult = stringValue;
                GameObject.Find("LoginManager").GetComponent<LogManager>().ReceiveIDExist(int.Parse(IDExistResult)); // 계정생성
                break;
            case protocol_Upload:
                Debug.LogWarning("protocol_Upload");
                string ResultUpLoad = stringValue;
                Debug.Log(ResultUpLoad);
                break;
            case protocol_IndividualRank:
                Debug.LogWarning("protocol_IndividualRank");
                string ResultIndividualRank = stringValue;
                Debug.Log(ResultIndividualRank);
                break;
            case protocol_RoomMake:
                Debug.LogWarning("protocol_RoomMake");
                string RoomMake = stringValue;
                GameObject.Find("LoginManager").GetComponent<RoomControll>().ReceiveRoomMake(int.Parse(RoomMake)); 
                break;
            case protocol_RoomOut:
                Debug.LogWarning("protocol_RoomOut");
                string RoomOut = stringValue;
                GameObject.Find("LoginManager").GetComponent<RoomControll>().ReceiveRoomOut(int.Parse(RoomOut));
                break;
            case protocol_RoomList:
                Debug.LogWarning("protocol_RoomList");
                Debug.Log(3);
                break;
            case protocol_RoomInfo:
                Debug.LogWarning("protocol_RoomInfo");
                Debug.Log(4);
                break;
            case protocol_RoomJoin:
                Debug.LogWarning("protocol_RoomJoin");
                string RoomJoin = stringValue;
                GameObject.Find("LoginManager").GetComponent<RoomControll>().ReceiveRoomJoin(int.Parse(RoomJoin));
                break;
            case protocol_GameStart:
                Debug.LogWarning("protocol_GameStart");
                Debug.Log(6);
                break;
            case protocol_GameEnd:
                Debug.LogWarning("protocol_GameEnd");
                string GameEnd = stringValue;
                Debug.Log(GameEnd);
                break;
            case 100:
                Debug.LogWarning("100");
                // test code
                ReceiveWebjsonProcess(id, www);
                break;
            default:
                Debug.LogWarning("default");
                ReceiveWebjsonProcess(id, www);
                break;
        }
        //if(id == 0)
        //    stringValue = Encoding.UTF8.GetString ( Convert.FromBase64String ( stringValue ) );
        try {
            jsonDataS = JSON.Parse (stringValue);
        } catch {
            jsonDataS = null;
            #if UNITY_EDITOR
                Debug.LogError("json parse fail");
            #endif
        }
        ReceiveDataToJSon(id, jsonDataS);
    }
    public void ReceiveDataToJSon(int _nCmd, JSONNode _data)
    {
        if (_data != null)
        {
            // _nCmd = System.Int32.Parse(_data["CODE"].Value); 
            // Debug.LogError("_nCmd : " + _nCmd);
            switch (_nCmd)
            {
                // ====================================================================================================
                // protocol_Begin
                // ====================================================================================================
                case protocol_Begin:
                    Debug.LogWarning("protocol_Begin");
                    string Beginresult = _data["RESULT"].Value;
                    string Beginmessage = _data["MESSAGE"].Value;
                    string Beginexchistid = _data["EXCHISTID"].Value;
                    Debug.LogError("RESULT: " + Beginresult);
                    Debug.LogError("MESSAGE: " + Beginmessage);
                    Debug.LogError("EXCHISTID: " + Beginexchistid);
                    PlayerPrefs.SetString("EXCHISTID",Beginexchistid);
                    string EXCHISTID = Beginexchistid;
                    
                    break;
                // ====================================================================================================
                // protocol_End
                // ====================================================================================================
                case protocol_End:
                    Debug.LogWarning("protocol_End");
                    string Endresult = _data["RESULT"].Value;
                    string Endmessage = _data["MESSAGE"].Value;
                    string Endexchistid = _data["EXCHISTID"].Value;
                    Debug.LogError("RESULT: " + Endresult);
                    Debug.LogError("MESSAGE: " + Endmessage);
                    Debug.LogError("EXCHISTID: " + Endexchistid);
                    break;
                // ====================================================================================================
                // protocol_RoomList
                // ====================================================================================================
                case protocol_RoomList:
                    Debug.LogWarning("protocol_RoomList");
                    string roomlist = _data["RESULT"].Value;
                    JSONNode jsonData_red = _data["roomList"];
                    GameObject.Find("LoginManager").GetComponent<RoomControll>().SetRoomList(jsonData_red);
                    break;
                // ====================================================================================================
                // protocol_RoomInfo
                // ====================================================================================================
                case protocol_RoomInfo:
                    Debug.LogWarning("protocol_RoomInfo");
                    string roomInfo = _data["RESULT"].Value;
                    JSONNode jsonData = _data["room"];
                    Scene m_Scene = SceneManager.GetActiveScene();
                    if (m_Scene.name == "LobbyScene")
                        GameObject.Find("LoginManager").GetComponent<RoomControll>().RoomStateInfo(jsonData);
                    else if (m_Scene.name == "ResultScene")
                        GameObject.Find("EndResultManager").GetComponent<EndResult>().RoomStateInfo(jsonData);
                    break;
                default:
                    break;
            }
            if (_nCmd == 0)
            {
                try
                {
                }
                catch (Exception e)
                {
                    Debug.Log(e);
                }
            }
            else
            {
            }
        }
    }
   
    // ====================================================================================================
    // pathForDocumentsFile
    // ====================================================================================================
    public string pathForDocumentsFile(string filename)
    {
        if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            string path = Application.dataPath.Substring(0, Application.dataPath.Length - 5);
            path = path.Substring(0, path.LastIndexOf('/'));
            return Path.Combine(Path.Combine(path, "Documents"), filename);
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            string path = Application.persistentDataPath;
            path = path.Substring(0, path.LastIndexOf('/'));
            return Path.Combine(path, filename);
        }
        else
        {
            string path = Application.dataPath;
            path = path.Substring(0, path.LastIndexOf('/'));
            return Path.Combine(path, filename);
        }
    }
    // ====================================================================================================
    // writeStringToFile
    // ====================================================================================================
    public void writeStringToFile(string str, string filename)
    {
#if !WEB_BUILD
        string path = pathForDocumentsFile(filename);
        FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write);
        StreamWriter sw = new StreamWriter(file);
        sw.WriteLine(str);
        sw.Close();
        file.Close();
#endif
    }
    // ====================================================================================================
    // readStringFromFile
    // ====================================================================================================
    public string readStringFromFile(string filename)//, int lineIndex )
    {
#if !WEB_BUILD
        string path = pathForDocumentsFile(filename);
        if (File.Exists(path))
        {
            FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(file);
            string str = null;
            str = sr.ReadLine();
            sr.Close();
            file.Close();
            return str;
        }
        else
        {
            return null;
        }
#else
return null;
#endif
    }
    // ====================================================================================================
    // Encoding Decoding
    // ====================================================================================================
    public static string EncodingData (string text) {
        string s = text;
        Debug.Log("원본문자열 : " + s);
        
        // 코드페이지 번호는 http://msdn.microsoft.com/ko-kr/library/system.text.encoding.aspx 에서 확인하시면 됩니다.
        int euckrCodepage = 51949;
        
        // 인코딩을 편리하게 해주기 위해서 인코딩클래스 변수를 만듭니다.
        System.Text.Encoding defaut = System.Text.Encoding.Default;
        System.Text.Encoding ascii = System.Text.Encoding.ASCII;
        System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
        System.Text.Encoding euckr = System.Text.Encoding.GetEncoding(euckrCodepage);
        
        // 위에서 만든 변수를 이용하여 Byte의 배열로 문자열을 인코딩하여 얻는 부분입니다.
        byte[] defautBytes = defaut.GetBytes(s);
        Debug.Log("Default : ");
        foreach (byte b in defautBytes)
        {
            Debug.Log(" 0 :  " + b); // byte를 16진수로 표기합니다.
        }
        Debug.Log("\n");
        byte[] asciiBytes = ascii.GetBytes(s);
        Debug.Log("ASCII : ");
        foreach (byte b in asciiBytes)
        {
            Debug.Log(" 0 :  " + b); // byte를 16진수로 표기합니다.
        }
        Debug.Log("\n");
        byte[] utf8Bytes = utf8.GetBytes(s);
        Debug.Log("UTF-8 : ");
        foreach (byte b in utf8Bytes)
        {
            Debug.Log(" 0 :  " + b); // byte를 16진수로 표기합니다.
        }
        Debug.Log("\n");
        
        byte[] euckrBytes = euckr.GetBytes(s);
        Debug.Log("EUC-KR : ");
        foreach (byte b in euckrBytes)
        {
            Debug.Log(" 1 : " + b); // byte를 16진수로 표기합니다.
        }
        Debug.Log("\n");
        
        
        // 인코딩된것을 문자열로 변환하기
        string decodedStringByDefault = defaut.GetString(defautBytes);
        string decodedStringByASCII = ascii.GetString(asciiBytes);
        string decodedStringByEUCKR = euckr.GetString(euckrBytes);
        string decodedStringByUTF8 = utf8.GetString(utf8Bytes);
        Debug.Log("Default로 디코딩된 문자열 : " + decodedStringByDefault);
        Debug.Log("ASCII로 디코딩된 문자열 : " + decodedStringByASCII);
        Debug.Log("EUC-KR로 디코딩된 문자열 : " + decodedStringByEUCKR);
        Debug.Log("UTF-8로 디코딩된 문자열 : " + decodedStringByUTF8);
        return decodedStringByDefault;
        
        
        // =====
    }
    public static string StringToEncoding(String str)
    {
        Encoding encode = System.Text.Encoding.GetEncoding("euc-kr");
        byte[] byteencode = encode.GetBytes(str);
        
        return encode.GetString(byteencode, 0, byteencode.Length);
    }
    public static string DencodingData(string text) {
        byte[] byte_Decoded = Convert.FromBase64String (text);
        string strDecodedData = Encoding.UTF8.GetString (byte_Decoded);
        
        return strDecodedData;
    }
    #endregion
    // ====================================================================================================
    // ====================================================================================================
    // ====================================================================================================
    // ====================================================================================================
cs

SimpleJSON

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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
//#define USE_SharpZipLib
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
/* * * * *
 * A simple JSON Parser / builder
 * ------------------------------
 * 
 * It mainly has been written as a simple JSON parser. It can build a JSON string
 * from the node-tree, or generate a node tree from any valid JSON string.
 * 
 * If you want to use compression when saving to file / stream / B64 you have to include
 * SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
 * define "USE_SharpZipLib" at the top of the file
 * 
 * Written by Bunny83 
 * 2012-06-09
 * 
 * Features / attributes:
 * - provides strongly typed node classes and lists / dictionaries
 * - provides easy access to class members / array items / data values
 * - the parser ignores data types. Each value is a string.
 * - only double quotes (") are used for quoting strings.
 * - values and names are not restricted to quoted strings. They simply add up and are trimmed.
 * - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
 * - provides "casting" properties to easily convert to / from those types:
 *   int / float / double / bool
 * - provides a common interface for each node so no explicit casting is required.
 * - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
 * 
 * 
 * 2012-12-17 Update:
 * - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
 *   Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
 *   The class determines the required type by it's further use, creates the type and removes itself.
 * - Added binary serialization / deserialization.
 * - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
 *   The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
 * - The serializer uses different types when it comes to store the values. Since my data values
 *   are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
 *   It's not the most efficient way but for a moderate amount of data it should work on all platforms.
 * 
 * * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SimpleJSON
{
    public enum JSONBinaryTag
    {
        Array            = 1,
        Class            = 2,
        Value            = 3,
        IntValue        = 4,
        DoubleValue        = 5,
        BoolValue        = 6,
        FloatValue        = 7,
    }
    public class JSONNode
    {
        #region common interface
        public virtual void Add(string aKey, JSONNode aItem){ }
        public virtual JSONNode this[int aIndex]   { get { return null; } set { } }
        public virtual JSONNode this[string aKey]  { get { return null; } set { } }
        public virtual string Value                { get { return "";   } set { } }
        public virtual int Count                   { get { return 0;    } }
        public virtual void Add(JSONNode aItem)
        {
            Add("", aItem);
        }
        public virtual JSONNode Remove(string aKey) { return null; }
        public virtual JSONNode Remove(int aIndex) { return null; }
        public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
        public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
        public IEnumerable<JSONNode> DeepChilds
        {
            get
            {
                foreach (var C in Childs)
                    foreach (var D in C.DeepChilds)
                        yield return D;
            }
        }
        public override string ToString()
        {
            return "JSONNode";
        }
        public virtual string ToString(string aPrefix)
        {
            return "JSONNode";
        }
        #endregion common interface
        #region typecasting properties
        public virtual int AsInt
        {
            get
            {
                int v = 0;
                if (int.TryParse(Value,out v))
                    return v;
                return 0;
            }
            set
            {
                Value = value.ToString();
            }
        }
        public virtual float AsFloat
        {
            get
            {
                float v = 0.0f;
                if (float.TryParse(Value,out v))
                    return v;
                return 0.0f;
            }
            set
            {
                Value = value.ToString();
            }
        }
        public virtual double AsDouble
        {
            get
            {
                double v = 0.0;
                if (double.TryParse(Value,out v))
                    return v;
                return 0.0;
            }
            set
            {
                Value = value.ToString();
            }
        }
        public virtual bool AsBool
        {
            get
            {
                bool v = false;
                if (bool.TryParse(Value,out v))
                    return v;
                return !string.IsNullOrEmpty(Value);
            }
            set
            {
                Value = (value)?"true":"false";
            }
        }
        public virtual JSONArray AsArray
        {
            get
            {
                return this as JSONArray;
            }
        }
        public virtual JSONClass AsObject
        {
            get
            {
                return this as JSONClass;
            }
        }
        #endregion typecasting properties
        #region operators
        public static implicit operator JSONNode(string s)
        {
            return new JSONData(s);
        }
        public static implicit operator string(JSONNode d)
        {
            return (d == null)?null:d.Value;
        }
        public static bool operator ==(JSONNode a, object b)
        {
            if (b == null && a is JSONLazyCreator)
                return true;
            return System.Object.ReferenceEquals(a,b);
        }
        public static bool operator !=(JSONNode a, object b)
        {
            return !(a == b);
        }
        public override bool Equals (object obj)
        {
            return System.Object.ReferenceEquals(this, obj);
        }
        public override int GetHashCode ()
        {
            return base.GetHashCode();
        }
        #endregion operators
        internal static string Escape(string aText)
        {
            string result = "";
            foreach(char c in aText)
            {
                switch(c)
                {
                    case '\\' : result += "\\\\"break;
                    case '\"' : result += "\\\""; break;
                    case '\n' : result += "\\n" ; break;
                    case '\r' : result += "\\r" ; break;
                    case '\t' : result += "\\t" ; break;
                    case '\b' : result += "\\b" ; break;
                    case '\f' : result += "\\f" ; break;
                    default   : result += c     ; break;
                }
            }
            return result;
        }
        public static JSONNode Parse(string aJSON)
        {
            Stack<JSONNode> stack = new Stack<JSONNode>();
            JSONNode ctx = null;
            int i = 0;
            string Token = "";
            string TokenName = "";
            bool QuoteMode = false;
            while (i < aJSON.Length)
            {
                switch (aJSON[i])
                {
                    case '{':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        stack.Push(new JSONClass());
                        if (ctx != null)
                        {
                            TokenName = TokenName.Trim();
                            if (ctx is JSONArray)
                                ctx.Add(stack.Peek());
                            else if (TokenName != "")
                                ctx.Add(TokenName,stack.Peek());
                        }
                        TokenName = "";
                        Token = "";
                        ctx = stack.Peek();
                    break;
                    case '[':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        stack.Push(new JSONArray());
                        if (ctx != null)
                        {
                            TokenName = TokenName.Trim();
                            if (ctx is JSONArray)
                                ctx.Add(stack.Peek());
                            else if (TokenName != "")
                                ctx.Add(TokenName,stack.Peek());
                        }
                        TokenName = "";
                        Token = "";
                        ctx = stack.Peek();
                    break;
                    case '}':
                    case ']':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        if (stack.Count == 0)
                            throw new Exception("JSON Parse: Too many closing brackets");
                        stack.Pop();
                        if (Token != "")
                        {
                            TokenName = TokenName.Trim();
                            if (ctx is JSONArray)
                                ctx.Add(Token);
                            else if (TokenName != "")
                                ctx.Add(TokenName,Token);
                        }
                        TokenName = "";
                        Token = "";
                        if (stack.Count>0)
                            ctx = stack.Peek();
                    break;
                    case ':':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        TokenName = Token;
                        Token = "";
                    break;
                    case '"':
                        QuoteMode ^= true;
                    break;
                    case ',':
                        if (QuoteMode)
                        {
                            Token += aJSON[i];
                            break;
                        }
                        if (Token != "")
                        {
                            if (ctx is JSONArray)
                                ctx.Add(Token);
                            else if (TokenName != "")
                                ctx.Add(TokenName, Token);
                        }
                        TokenName = "";
                        Token = "";
                    break;
                    case '\r':
                    case '\n':
                    break;
                    case ' ':
                    case '\t':
                        if (QuoteMode)
                            Token += aJSON[i];
                    break;
                    case '\\':
                        ++i;
                        if (QuoteMode)
                        {
                            char C = aJSON[i];
                            switch (C)
                            {
                                case 't' : Token += '\t'; break;
                                case 'r' : Token += '\r'; break;
                                case 'n' : Token += '\n'; break;
                                case 'b' : Token += '\b'; break;
                                case 'f' : Token += '\f'; break;
                                case 'u':
                                {
                                    string s = aJSON.Substring(i+1,4);
                                    Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
                                    i += 4;
                                    break;
                                }
                                default  : Token += C; break;
                            }
                        }
                    break;
                    default:
                        Token += aJSON[i];
                    break;
                }
                ++i;
            }
            if (QuoteMode)
            {
                throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
            }
            return ctx;
        }
        public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
        public void SaveToStream(System.IO.Stream aData)
        {
            var W = new System.IO.BinaryWriter(aData);
            Serialize(W);
        }
        #if USE_SharpZipLib
        public void SaveToCompressedStream(System.IO.Stream aData)
        {
            using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
            {
                gzipOut.IsStreamOwner = false;
                SaveToStream(gzipOut);
                gzipOut.Close();
            }
        }
        public void SaveToCompressedFile(string aFileName)
        {
            #if USE_FileIO
            System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
            using(var F = System.IO.File.OpenWrite(aFileName))
            {
                SaveToCompressedStream(F);
            }
            #else
            throw new Exception("Can't use File IO stuff in webplayer");
            #endif
        }
        public string SaveToCompressedBase64()
        {
            using (var stream = new System.IO.MemoryStream())
            {
                SaveToCompressedStream(stream);
                stream.Position = 0;
                return System.Convert.ToBase64String(stream.ToArray());
            }
        }
        #else
        public void SaveToCompressedStream(System.IO.Stream aData)
        {
            throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
        }
        public void SaveToCompressedFile(string aFileName)
        {
            throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
        }
        public string SaveToCompressedBase64()
        {
            throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
        }
        #endif
        
        public void SaveToFile(string aFileName)
        {
            #if USE_FileIO
            System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
            using(var F = System.IO.File.OpenWrite(aFileName))
            {
                SaveToStream(F);
            }
            #else
            throw new Exception("Can't use File IO stuff in webplayer");
            #endif
        }
        public string SaveToBase64()
        {
            using (var stream = new System.IO.MemoryStream())
            {
                SaveToStream(stream);
                stream.Position = 0;
                return System.Convert.ToBase64String(stream.ToArray());
            }
        }
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
            switch(type)
            {
            case JSONBinaryTag.Array:
            {
                int count = aReader.ReadInt32();
                JSONArray tmp = new JSONArray();
                for(int i = 0; i < count; i++)
                    tmp.Add(Deserialize(aReader));
                return tmp;
            }
            case JSONBinaryTag.Class:
            {
                int count = aReader.ReadInt32();                
                JSONClass tmp = new JSONClass();
                for(int i = 0; i < count; i++)
                {
                    string key = aReader.ReadString();
                    var val = Deserialize(aReader);
                    tmp.Add(key, val);
                }
                return tmp;
            }
            case JSONBinaryTag.Value:
            {
                return new JSONData(aReader.ReadString());
            }
            case JSONBinaryTag.IntValue:
            {
                return new JSONData(aReader.ReadInt32());
            }
            case JSONBinaryTag.DoubleValue:
            {
                return new JSONData(aReader.ReadDouble());
            }
            case JSONBinaryTag.BoolValue:
            {
                return new JSONData(aReader.ReadBoolean());
            }
            case JSONBinaryTag.FloatValue:
            {
                return new JSONData(aReader.ReadSingle());
            }
            default:
            {
                throw new Exception("Error deserializing JSON. Unknown tag: " + type);
            }
            }
        }
        #if USE_SharpZipLib
        public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
        {
            var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
            return LoadFromStream(zin);
        }
        public static JSONNode LoadFromCompressedFile(string aFileName)
        {
            #if USE_FileIO
            using(var F = System.IO.File.OpenRead(aFileName))
            {
                return LoadFromCompressedStream(F);
            }
            #else
            throw new Exception("Can't use File IO stuff in webplayer");
            #endif
        }
        public static JSONNode LoadFromCompressedBase64(string aBase64)
        {
            var tmp = System.Convert.FromBase64String(aBase64);
            var stream = new System.IO.MemoryStream(tmp);
            stream.Position = 0;
            return LoadFromCompressedStream(stream);
        }
        #else
        public static JSONNode LoadFromCompressedFile(string aFileName)
        {
            throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
        }
        public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
        {
            throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
        }
        public static JSONNode LoadFromCompressedBase64(string aBase64)
        {
            throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
        }
        #endif
        public static JSONNode LoadFromStream(System.IO.Stream aData)
        {
            using(var R = new System.IO.BinaryReader(aData))
            {
                return Deserialize(R);
            }
        }
        public static JSONNode LoadFromFile(string aFileName)
        {
            #if USE_FileIO
            using(var F = System.IO.File.OpenRead(aFileName))
            {
                return LoadFromStream(F);
            }
            #else
            throw new Exception("Can't use File IO stuff in webplayer");
            #endif
        }
        public static JSONNode LoadFromBase64(string aBase64)
        {
            var tmp = System.Convert.FromBase64String(aBase64);
            var stream = new System.IO.MemoryStream(tmp);
            stream.Position = 0;
            return LoadFromStream(stream);
        }
    } // End of JSONNode
    public class JSONArray : JSONNode, IEnumerable
    {
        private List<JSONNode> m_List = new List<JSONNode>();
        public override JSONNode this[int aIndex]
        {
            get
            {
                if (aIndex<0 || aIndex >= m_List.Count)
                    return new JSONLazyCreator(this);
                return m_List[aIndex];
            }
            set
            {
                if (aIndex<0 || aIndex >= m_List.Count)
                    m_List.Add(value);
                else
                    m_List[aIndex] = value;
            }
        }
        public override JSONNode this[string aKey]
        {
            get{ return new JSONLazyCreator(this);}
            set{ m_List.Add(value); }
        }
        public override int Count
        {
            get { return m_List.Count; }
        }
        public override void Add(string aKey, JSONNode aItem)
        {
            m_List.Add(aItem);
        }
        public override JSONNode Remove(int aIndex)
        {
            if (aIndex < 0 || aIndex >= m_List.Count)
                return null;
            JSONNode tmp = m_List[aIndex];
            m_List.RemoveAt(aIndex);
            return tmp;
        }
        public override JSONNode Remove(JSONNode aNode)
        {
            m_List.Remove(aNode);
            return aNode;
        }
        public override IEnumerable<JSONNode> Childs
        {
            get
            {
                foreach(JSONNode N in m_List)
                    yield return N;
            }
        }
        public IEnumerator GetEnumerator()
        {
            foreach(JSONNode N in m_List)
                yield return N;
        }
        public override string ToString()
        {
            string result = "[ ";
            foreach (JSONNode N in m_List)
            {
                if (result.Length > 2)
                    result += ", ";
                result += N.ToString();
            }
            result += " ]";
            return result;
        }
        public override string ToString(string aPrefix)
        {
            string result = "[ ";
            foreach (JSONNode N in m_List)
            {
                if (result.Length > 3)
                    result += ", ";
                result += "\n" + aPrefix + "   ";                
                result += N.ToString(aPrefix+"   ");
            }
            result += "\n" + aPrefix + "]";
            return result;
        }
        public override void Serialize (System.IO.BinaryWriter aWriter)
        {
            aWriter.Write((byte)JSONBinaryTag.Array);
            aWriter.Write(m_List.Count);
            for(int i = 0; i < m_List.Count; i++)
            {
                m_List[i].Serialize(aWriter);
            }
        }
    } // End of JSONArray
    public class JSONClass : JSONNode, IEnumerable
    {
        private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
        public override JSONNode this[string aKey]
        {
            get
            {
                if (m_Dict.ContainsKey(aKey))
                    return m_Dict[aKey];
                else
                    return new JSONLazyCreator(this, aKey);
            }
            set
            {
                if (m_Dict.ContainsKey(aKey))
                    m_Dict[aKey] = value;
                else
                    m_Dict.Add(aKey,value);
            }
        }
        public override JSONNode this[int aIndex]
        {
            get
            {
                if (aIndex < 0 || aIndex >= m_Dict.Count)
                    return null;
                return m_Dict.ElementAt(aIndex).Value;
            }
            set
            {
                if (aIndex < 0 || aIndex >= m_Dict.Count)
                    return;
                string key = m_Dict.ElementAt(aIndex).Key;
                m_Dict[key] = value;
            }
        }
        public override int Count
        {
            get { return m_Dict.Count; }
        }
        public override void Add(string aKey, JSONNode aItem)
        {
            if (!string.IsNullOrEmpty(aKey))
            {
                if (m_Dict.ContainsKey(aKey))
                    m_Dict[aKey] = aItem;
                else
                    m_Dict.Add(aKey, aItem);
            }
            else
                m_Dict.Add(Guid.NewGuid().ToString(), aItem);
        }
        public override JSONNode Remove(string aKey)
        {
            if (!m_Dict.ContainsKey(aKey))
                return null;
            JSONNode tmp = m_Dict[aKey];
            m_Dict.Remove(aKey);
            return tmp;        
        }
        public override JSONNode Remove(int aIndex)
        {
            if (aIndex < 0 || aIndex >= m_Dict.Count)
                return null;
            var item = m_Dict.ElementAt(aIndex);
            m_Dict.Remove(item.Key);
            return item.Value;
        }
        public override JSONNode Remove(JSONNode aNode)
        {
            try
            {
                var item = m_Dict.Where(k => k.Value == aNode).First();
                m_Dict.Remove(item.Key);
                return aNode;
            }
            catch
            {
                return null;
            }
        }
        public override IEnumerable<JSONNode> Childs
        {
            get
            {
                foreach(KeyValuePair<string,JSONNode> N in m_Dict)
                    yield return N.Value;
            }
        }
        public IEnumerator GetEnumerator()
        {
            foreach(KeyValuePair<string, JSONNode> N in m_Dict)
                yield return N;
        }
        public override string ToString()
        {
            string result = "{";
            foreach (KeyValuePair<string, JSONNode> N in m_Dict)
            {
                if (result.Length > 2)
                    result += ", ";
                result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
            }
            result += "}";
            return result;
        }
        public override string ToString(string aPrefix)
        {
            string result = "{ ";
            foreach (KeyValuePair<string, JSONNode> N in m_Dict)
            {
                if (result.Length > 3)
                    result += ", ";
                result += "\n" + aPrefix + "   ";
                result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+"   ");
            }
            result += "\n" + aPrefix + "}";
            return result;
        }
        public override void Serialize (System.IO.BinaryWriter aWriter)
        {
            aWriter.Write((byte)JSONBinaryTag.Class);
            aWriter.Write(m_Dict.Count);
            foreach(string K in m_Dict.Keys)
            {
                aWriter.Write(K);
                m_Dict[K].Serialize(aWriter);
            }
        }
    } // End of JSONClass
    public class JSONData : JSONNode
    {
        private string m_Data;
        public override string Value
        {
            get { return m_Data; }
            set { m_Data = value; }
        }
        public JSONData(string aData)
        {
            m_Data = aData;
        }
        public JSONData(float aData)
        {
            AsFloat = aData;
        }
        public JSONData(double aData)
        {
            AsDouble = aData;
        }
        public JSONData(bool aData)
        {
            AsBool = aData;
        }
        public JSONData(int aData)
        {
            AsInt = aData;
        }
        public override string ToString()
        {
            return "\"" + Escape(m_Data) + "\"";
        }
        public override string ToString(string aPrefix)
        {
            return "\"" + Escape(m_Data) + "\"";
        }
        public override void Serialize (System.IO.BinaryWriter aWriter)
        {
            var tmp = new JSONData("");
            tmp.AsInt = AsInt;
            if (tmp.m_Data == this.m_Data)
            {
                aWriter.Write((byte)JSONBinaryTag.IntValue);
                aWriter.Write(AsInt);
                return;
            }
            tmp.AsFloat = AsFloat;
            if (tmp.m_Data == this.m_Data)
            {
                aWriter.Write((byte)JSONBinaryTag.FloatValue);
                aWriter.Write(AsFloat);
                return;
            }
            tmp.AsDouble = AsDouble;
            if (tmp.m_Data == this.m_Data)
            {
                aWriter.Write((byte)JSONBinaryTag.DoubleValue);
                aWriter.Write(AsDouble);
                return;
            }
            tmp.AsBool = AsBool;
            if (tmp.m_Data == this.m_Data)
            {
                aWriter.Write((byte)JSONBinaryTag.BoolValue);
                aWriter.Write(AsBool);
                return;
            }
            aWriter.Write((byte)JSONBinaryTag.Value);
            aWriter.Write(m_Data);
        }
    } // End of JSONData
    internal class JSONLazyCreator : JSONNode
    {
        private JSONNode m_Node = null;
        private string m_Key = null;
        public JSONLazyCreator(JSONNode aNode)
        {
            m_Node = aNode;
            m_Key  = null;
        }
        public JSONLazyCreator(JSONNode aNode, string aKey)
        {
            m_Node = aNode;
            m_Key = aKey;
        }
        private void Set(JSONNode aVal)
        {
            if (m_Key == null)
            {
                m_Node.Add(aVal);
            }
            else
            {
                m_Node.Add(m_Key, aVal);
            }
            m_Node = null; // Be GC friendly.
        }
        public override JSONNode this[int aIndex]
        {
            get
            {
                return new JSONLazyCreator(this);
            }
            set
            {
                var tmp = new JSONArray();
                tmp.Add(value);
                Set(tmp);
            }
        }
        public override JSONNode this[string aKey]
        {
            get
            {
                return new JSONLazyCreator(this, aKey);
            }
            set
            {
                var tmp = new JSONClass();
                tmp.Add(aKey, value);
                Set(tmp);
            }
        }
        public override void Add (JSONNode aItem)
        {
            var tmp = new JSONArray();
            tmp.Add(aItem);
            Set(tmp);
        }
        public override void Add (string aKey, JSONNode aItem)
        {
            var tmp = new JSONClass();
            tmp.Add(aKey, aItem);
            Set(tmp);
        }
        public static bool operator ==(JSONLazyCreator a, object b)
        {
            if (b == null)
                return true;
            return System.Object.ReferenceEquals(a,b);
        }
        public static bool operator !=(JSONLazyCreator a, object b)
        {
            return !(a == b);
        }
        public override bool Equals (object obj)
        {
            if (obj == null)
                return true;
            return System.Object.ReferenceEquals(this, obj);
        }
        public override int GetHashCode ()
        {
            return base.GetHashCode();
        }
        public override string ToString()
        {
            return "";
        }
        public override string ToString(string aPrefix)
        {
            return "";
        }
        public override int AsInt
        {
            get
            {
                JSONData tmp = new JSONData(0);
                Set(tmp);
                return 0;
            }
            set
            {
                JSONData tmp = new JSONData(value);
                Set(tmp);
            }
        }
        public override float AsFloat
        {
            get
            {
                JSONData tmp = new JSONData(0.0f);
                Set(tmp);
                return 0.0f;
            }
            set
            {
                JSONData tmp = new JSONData(value);
                Set(tmp);
            }
        }
        public override double AsDouble
        {
            get
            {
                JSONData tmp = new JSONData(0.0);
                Set(tmp);
                return 0.0;
            }
            set
            {
                JSONData tmp = new JSONData(value);
                Set(tmp);
            }
        }
        public override bool AsBool
        {
            get
            {
                JSONData tmp = new JSONData(false);
                Set(tmp);
                return false;
            }
            set
            {
                JSONData tmp = new JSONData(value);
                Set(tmp);
            }
        }
        public override JSONArray AsArray
        {
            get
            {
                JSONArray tmp = new JSONArray();
                Set(tmp);
                return tmp;
            }
        }
        public override JSONClass AsObject
        {
            get
            {
                JSONClass tmp = new JSONClass();
                Set(tmp);
                return tmp;
            }
        }
    } // End of JSONLazyCreator
    public static class JSON
    {
        public static JSONNode Parse(string aJSON)
        {
            return JSONNode.Parse(aJSON);
        }
    }
}
cs


httpManager

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
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using SimpleJSON;
public class HttpManager: MonoBehaviour {
    public delegate void NetworkEndDelegate(JSONNode _networkRecv, int returnIndex);
    /** 이벤트 연결을 위한 델리게이터 (대기자) */
    public delegate void HttpRequestDelegate(int id, WWW www);
    
    /** 이벤트 핸들러 */
    public event HttpRequestDelegate OnHttpRequest;
    
    /** 웹 서버로의 요청을 구분하기 위한 ID값 */
    private int requestId;
    
    /** 이 클래스의 싱글톤 객체 */
    static HttpManager current = null;
    
    /** 객체를 생성하기 위한 GameObject */
    static GameObject container = null;
    
    /** 싱글톤 객체 만들기 */
    public static HttpManager Instance {
        get {
            if (current == null) {
                container = new GameObject();
                container.name = "http";
                current = container.AddComponent(typeof(HttpManager)) as HttpManager;
            }
            return current;
        }
    }
    
    /** HTTP GET 방식 통신 처리 */
    public void get(int id, string url) {
        WWW www = new WWW(url);
        StartCoroutine(WaitForRequest1(id, www));
    }
    
    /** HTTP POST 방식 통신 처리 */
    public void post(int id, string url, IDictionary<stringstring> data)
    {
        WWWForm form = new WWWForm();
        foreach (KeyValuePair<stringstring> post_arg in data)
        {
            form.AddField(post_arg.Key, post_arg.Value);
            Debug.LogError("Key: " + post_arg.Key + " ========== " + "Value: " + post_arg.Value);
            //Debug.LogError(post_arg.Key);
        }
        
        WWW www = new WWW(url, form);
        StartCoroutine(WaitForRequest(id, www));
    }
    public void post(int id, string url, IDictionary<stringint> data)
    {
        WWWForm form = new WWWForm();
        foreach (KeyValuePair<stringint> post_arg in data)
        {
            form.AddField(post_arg.Key, post_arg.Value);
            Debug.LogError(post_arg.Value);
            Debug.LogError(post_arg.Key);
        }
        WWW www = new WWW(url, form);
        StartCoroutine(WaitForRequest(id, www));
    }
    public WWW POST(int id, string url, JSONNode post)
    {
        #if UNITY_EDITOR
        if (!Application.isPlaying)
            return null;
        #endif
        WWWForm form = new WWWForm();
        string jsonToString = post.ToString ();
        //#if UNITY_EDITOR
        Debug.Log("jsonToString : " + url + jsonToString.ToString());
        //#endif
        form.AddField ("enc""0");
        form.AddField("param", jsonToString);
        
        WWW www = new WWW(url, form);
        StartCoroutine(WaitForRequest(id, www));
        
        return www; 
    }
    
    /** 통신 처리를 위한 코루틴 */
    private IEnumerator  WaitForRequest(int id, WWW www) {
        // 응답이 올떄까지 기다림
        yield return www;
        
        // 응답이 왔다면, 이벤트 리스너에 응답 결과 전달
        bool hasCompleteListener = (OnHttpRequest != null);
        
        if (hasCompleteListener) {
            OnHttpRequest(id, www);
        }
        Debug.Log("www : " +www.text);
        Debug.Log("==============================================================================================================");
        // 통신 해제
        www.Dispose();
    }
    private IEnumerator WaitForRequest1(int pw, WWW www)
    {
        // 응답이 올떄까지 기다림
        yield return www;
        // 응답이 왔다면, 이벤트 리스너에 응답 결과 전달
        bool hasCompleteListener = (OnHttpRequest != null);
        if (hasCompleteListener)
        {
            OnHttpRequest(pw, www);
        }
        Debug.Log("www : " + www.text);
        // 통신 해제
        www.Dispose();
    }
}
cs

https 버전 추가
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
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using UnityStandardAssets.CrossPlatformInput;
using System.Collections.Generic;
 
public class POST_Form : MonoBehaviour
{
 
    
    public static string PostForm(string url, IDictionary<stringstring> data)
    {
        ServicePointManager.ServerCertificateValidationCallback = TrustCertificate;
 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
 
        if (data != null)
        {
 
            StringBuilder postVars = new StringBuilder();
            
            foreach (string key in data.Keys)
            {
                postVars.AppendFormat("{0}={1}&", key, data[key]);
            }
 
            if ( postVars.Length > 0) postVars.Length -= 1// clip off the remaining &
 
            //This
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                streamWriter.Write(postVars.ToString());
        }
        WebResponse response = request.GetResponse();
 
        var sr = new StreamReader(response.GetResponseStream());
        string resString = sr.ReadToEnd();
        sr.Close();
        Debug.Log(resString);
 
        return resString;
        //Or this works
        /*var streamWriter = new StreamWriter (request.GetRequestStream ());
        streamWriter.Write (postVars.ToString());
        streamWriter.Close();*/
    }
 
    private static bool TrustCertificate(object sender, X509Certificate x509Certificate, X509Chain x509Chain, SslPolicyErrors sslPolicyErrors)
    {
        // all Certificates are accepted
        return true;
    }
}
 
cs

댓글