2020년 2월 27일 목요일

unity animation관련 (플레이 백, startTIme,endTime)

 #region animation관련 (플레이 백, startTIme,endTime)
    public void AnimationPlayAndBack(bool isOn)
    {
        Debug.Log("ani.clip.name:" + animation_Tutorials[0].clip.name);

        if (isOn)
        {
            animation_Tutorials[0][animation_Tutorials[0].clip.name].time = 0;
            animation_Tutorials[0][animation_Tutorials[0].clip.name].speed = 1;
            animation_Tutorials[0].Play(animation_Tutorials[0].clip.name);
        }
        else
        {
            animation_Tutorials[0][animation_Tutorials[0].clip.name].time = animation_Tutorials[0][animation_Tutorials[0].clip.name].length;
            animation_Tutorials[0][animation_Tutorials[0].clip.name].speed = -1;
            animation_Tutorials[0].Play(animation_Tutorials[0].clip.name);
        }
    }

    //public void AnimationPlay(float startTime,float endTime)
    //{
    //    animation_Tutorials[0][animation_Tutorials[0].clip.name].time = startTime;
    //    animation_Tutorials[0][animation_Tutorials[0].clip.name].speed = 1;
    //}

    public void OnAnimationPlayCustomTime(float startTime, float endTime)
    {
        if (cor_CustomAnimation != null)
        {
            StopCoroutine(cor_CustomAnimation);
            cor_CustomAnimation = null;
        }
        cor_CustomAnimation = cor_AnimationPlayCustomTime(startTime, endTime);
        StartCoroutine(cor_CustomAnimation);

        Animation_StartTimes.Enqueue(startTime);
    }

    public void OnAnimationPlayBackCustomTime(float startTime)
    {
        if (cor_CustomAnimationBack != null)
        {
            StopCoroutine(cor_CustomAnimationBack);
            cor_CustomAnimationBack = null;
        }
        cor_CustomAnimationBack = cor_AnimationBackPlayCustomTime(startTime);
        StartCoroutine(cor_CustomAnimationBack);
    }

    IEnumerator PlayBack()
    {
        while (Animation_StartTimes.Count > 0)
        {
            float startTime = Animation_StartTimes.Dequeue();
            float PlayTime = animation_Tutorials[0][animation_Tutorials[0].clip.name].time - startTime;
            OnAnimationPlayBackCustomTime(startTime);
            yield return new WaitForSeconds(PlayTime);
        }
    }

    IEnumerator cor_AnimationPlayCustomTime(float startTime, float endTime)
    {
        animation_Tutorials[0][animation_Tutorials[0].clip.name].time = startTime;
        animation_Tutorials[0][animation_Tutorials[0].clip.name].speed = 1;
        animation_Tutorials[0].Play(animation_Tutorials[0].clip.name);
        float playTime = endTime - startTime;
        yield return new WaitForSeconds(playTime);
        animation_Tutorials[0].Stop();
        animation_Tutorials[0][animation_Tutorials[0].clip.name].time = endTime;
    }

    IEnumerator cor_AnimationBackPlayCustomTime(float startTime)
    {
        float playTime = animation_Tutorials[0][animation_Tutorials[0].clip.name].time - startTime;
        animation_Tutorials[0][animation_Tutorials[0].clip.name].speed = -1;
        animation_Tutorials[0].Play(animation_Tutorials[0].clip.name);
        yield return new WaitForSeconds(playTime);
        animation_Tutorials[0].Stop();
        animation_Tutorials[0][animation_Tutorials[0].clip.name].time = startTime;
    }
    #endregion

2020년 2월 24일 월요일

C# 가장 긴 쿨타임 반환

void MostLongCooltime()
    {
        //Debug.Log("MostLongCooltime");
        ///비어있는 목록을 제거하고 있는 것들 중에서 max를 찾는다
        var filtered = skill_Infos.Where(x => x != null).ToArray();

        if (filtered == null)
            return;

        if (filtered.Length == 0)
            return;

        ///체크할께 하나밖에 없다면 모스트 쿨타임은 지금 현재쿨타임이다~
        if (filtered.Count() <= 1)
        {
            //Debug.Log("한개");
            MostCoolTime_Index = Array.IndexOf(skill_Infos, filtered[0]);

            //아이템의 쿨타임 감소 상한치는 0.7f 이다
            if (item_coolTimes[MostCoolTime_Index] > 0.7f)
            {
                item_coolTimes[MostCoolTime_Index] = 0.7f;
            }

            MostCoolTime_Value = filtered[0].coolTime;
            MostCoolTime_Value -= (MostCoolTime_Value * item_coolTimes[MostCoolTime_Index]);
            return;
        }
        //Debug.Log("transformName:" + transform.name);

        ///실제 쿨타임 계산 공식
        Skill_Info _info = skill_Infos.Where(x => (x != null&& (x.coolTime == filtered.Max(t => t.coolTime)))).First();

        MostCoolTime_Index = Array.IndexOf(skill_Infos, _info);

        if (item_coolTimes[MostCoolTime_Index] > 0.7f)
        {
            item_coolTimes[MostCoolTime_Index] = 0.7f;
        }

        MostCoolTime_Value = _info.coolTime;
        MostCoolTime_Value -= (MostCoolTime_Value * item_coolTimes[MostCoolTime_Index]);
    }

unity post processing

window>packageManager

에서

post processing 검색해서 설치

UI Layer에 PostProcessing 이 추가 안되있다면 추가

메인카메라에

Post Process Volume과

Post Process Layer를 추가하고

Volume에는 Profile을 추가하고

Layer에는 layer에 추가하고

모드도 Subpixel Morphological Anti-aliasin 으로 변경

2020년 2월 18일 화요일

c# dynamic 의미와 사용방법

일단 의미와 사용법을 알기에 앞서서 먼저 선행되어야 하는 지식인

런타임과 컴파일 타임에 대해서  여기 서 이해하고 오자


일단 핵심은

dynamic 형식은 컴파일 타임에 해석되지 않고 런타임에 해석된다.
그렇기 때문에 컴파일타임에 에러가 발생하지 않아 차후 에러에 원인분석에 어려움이 있을 수 있다.(런타임에 들어가야만 오류가 발생하기 때문에)

바로 이 지점에서 var와 dynamic이 많이 비교된다고 한다.

var apple = "사과"; Console.WriteLine(apple.Length); //apple를 치면 인텔리센스가 제시됩니다.

하지만 dynamic은 좀 다릅니다. dynamic은 object와 매우 유사하게 다루어집니다. 다음의 코드에서 컴파일러는 s.Length에 대해서는 아무런 판단도 하지 않습니다.
dynamic apple = "사과";
Console.WriteLine(apple.Length); //apple를 쳐도 인텔리센스가 제시되지 않습니다.
위의 코드는 런타임에 아무런 에러도 발생시키지 않겠지만 다음의 코드는 런타임에 에러를 발생시킵니다. 실행시 Brix 속성을 찾을수 없기 때문이죠.
dynamic apple = "사과";
Console.WriteLine(apple.Brix);


실제 프로그램 코딩시 dynamic타입은 메소드 파라메터로 자주 사용됩니다.
class Program
{    
    static void PrintValue(dynamic val)
    {
        Console.WriteLine(val.GetType());
    }

    static void Main(string[] args)
    {
        PrintValue("HelloWorld!");
        PrintValue(1000);
        PrintValue(10.50);
        PrintValue(true);
        PrintValue(DateTime.Now);
    }
}

프로젝트의 성공을 기원합니다.


출처: https://spaghetti-code.tistory.com/32 [어떻게 짤것인가]





Unirt C# 함수의 인자로 class 받기(제네릭)



인자로 받은 class가 원하는 타입의 클래스인지 확인후
dynamic 으로 원하는 obj를 담아서 사용
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


/// <summary> /// 여러 타입의 클래스를 이용한 데이터 파싱함수() /// </summary> /// <typeparam name="T"></typeparam> /// <param name="targetContents">적용할 UI 컨텐츠</param> /// <param name="target_roll_Unit_Infos">적용할 실제 데이터</param> /// <param name="sss">동적으로 적용할 클래스 타입(반 동적이라고 보면된다...없는거는 못함)</param> void CreateContents_Manual_Optimized<T>(Transform targetContents,List<Roll_Unit_Info> target_roll_Unit_Infos,T sss) where T:class
    {
        Contents_Init(targetContents);
        //PRODUCTION_SCHEDULE_GUIDANCE _guidance;
        dynamic currentList= null;
        if (sss.GetType() == typeof(Production_Schedule_Original))
        {
            Production_Schedule_Original tmpClass = sss as Production_Schedule_Original;
            currentList = tmpClass._PRODUCTION_SCHEDULE_ORIGINAL_ITEM;
        }
        else if (sss.GetType() == typeof(Production_Schedule_Optimized))
        {
            Production_Schedule_Optimized tmpClass = sss as Production_Schedule_Optimized;
            currentList = tmpClass._PRODUCTION_SCHEDULE_OPTIMIZED_ITEM;
        }
        else if (sss.GetType() == typeof(Production_Schedule_Manual_Optimized) )
        {
            Production_Schedule_Manual_Optimized tmpClass = sss as Production_Schedule_Manual_Optimized;
            currentList = tmpClass._PRODUCTION_SCHEDULE_MANUAL_OPTIMIZED_ITEM;
        }
        


## 사용
Production_Schedule_Original _Original;

CreateContents_Manual_Optimized(Original_Contents, Original_Infos, _Original);
        
        foreach (var x in currentList)
        {
cs




2020년 2월 17일 월요일

unity getcomponentsinchildren to list

1
2
3
4
5
6
7
8
9
  EquipSerialMove[] tmp = GetComponentsInChildren<EquipSerialMove>();
        foreach (var x in tmp)
        {
            equipSerialMoves.Add(x);
        }
cs

2020년 2월 13일 목요일

Object Pool 기법(Unity Gameobject) #오브젝트 풀



instantiate 와 destroy를 많이 하면 성능에 영향을 준다



objPool에다가 Gameobject를 담고
필요한 오브젝트의 gameobject setactive를 true와 false로 변경하면서 사용


ObjectPoolManager


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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPoolManager : MonoBehaviour {
    public static ObjectPoolManager current;
    private int offset = 1;
    public static Dictionary<stringList<GameObject>> PoolObjs;
    private void Awake()
    {
        current = this;
        PoolObjs = new Dictionary<stringList<GameObject>>();
    }
    public static GameObject CreateObj(GameObject _Prefab)
    {
        GameObject goQ = ObjectPoolManager.GetPooledObject(_Prefab);
        goQ.transform.parent = null;
        goQ.SetActive(true);
        return goQ;
    }
    public static GameObject CreateObj(GameObject _Prefab, Transform _Parent)
    {
        GameObject goQ = ObjectPoolManager.GetPooledObject(_Prefab, _Parent);
        goQ.SetActive(true);
        return goQ;
    }
    public static GameObject CreateObj(GameObject _Prefab, Vector3 pos, Quaternion rot)
    {
        GameObject goQ = ObjectPoolManager.GetPooledObject(_Prefab, pos, rot);
        goQ.transform.parent = null;
        goQ.SetActive(true);
        return goQ;
    }
    static void InitCreateObj(GameObject goType)
    {
        //이름이 중복되는 프리팹이 있다면 에러임 근데 그렇게 프리팹을 만든사람이 에러임 ㅇㅋ?
        PoolObjs.Add(goType.name, new List<GameObject>());
        for (int i = 0; i < 1; i++)
        {
            GameObject go = (GameObject)Instantiate(goType);
            go.name = goType.name;
            go.transform.parent = current.transform;
            go.GetComponent<PoolObj>().Original_Parent = current.transform;
            go.SetActive(false);
            PoolObjs[goType.name].Add(go);
        }
    }
    public static GameObject GetPooledObject(GameObject prefab)
    {
        if (!PoolObjs.ContainsKey(prefab.name))
        {
            InitCreateObj(prefab);
        }
        List<GameObject> PoolType = PoolObjs[prefab.name];
        for (int i = 0; i < PoolType.Count; i++)
        {
            if (!PoolType[i].activeInHierarchy)
            {
                return PoolType[i];
            }
        }
        AutoSizeUp(PoolType);
        return PoolType[PoolType.Count-1];
    }
    public static GameObject GetPooledObject(GameObject prefab,Transform parent)
    {
        if (!PoolObjs.ContainsKey(prefab.name))
        {
            InitCreateObj(prefab);
        }
        List<GameObject> PoolType = PoolObjs[prefab.name];
        for (int i = 0; i < PoolType.Count; i++)
        {
            if (!PoolType[i].activeInHierarchy)
            {
                PoolType[i].transform.parent = parent;
                return PoolType[i];
            }
        }
        AutoSizeUp(PoolType,parent);
        return PoolType[PoolType.Count - 1];
    }
    public static GameObject GetPooledObject(GameObject prefab,Vector3 pos,Quaternion rot)
    {
        if (!PoolObjs.ContainsKey(prefab.name))
        {
            InitCreateObj(prefab);
        }
        List<GameObject> PoolType = PoolObjs[prefab.name];
        for (int i = 0; i < PoolType.Count; i++)
        {
            if (!PoolType[i].activeInHierarchy)
            {
                PoolType[i].transform.position = pos;
                PoolType[i].transform.rotation = rot;
                PoolType[i].SetActive(true);
                return PoolType[i];
            }
        }
        AutoSizeUp(PoolType,pos,rot);
        PoolType[PoolType.Count - 1].SetActive(true);
        return PoolType[PoolType.Count - 1];
    }
    static void AutoSizeUp(List<GameObject> PoolType)
    {
        GameObject go = (GameObject)Instantiate(PoolType[0]);
        go.transform.parent = PoolType[0].GetComponent<PoolObj>().Original_Parent;
        go.name = PoolType[0].name;
        go.GetComponent<PoolObj>().Original_Parent = PoolType[0].GetComponent<PoolObj>().Original_Parent;
        PoolType.Add(go);
    }
    static void AutoSizeUp(List<GameObject> PoolType,Transform parent)
    {
        GameObject go = (GameObject)Instantiate(PoolType[0]);
        go.transform.parent = PoolType[0].GetComponent<PoolObj>().Original_Parent;
        go.name = PoolType[0].name;
        go.GetComponent<PoolObj>().Original_Parent = PoolType[0].GetComponent<PoolObj>().Original_Parent;
        go.transform.parent = parent;
        PoolType.Add(go);
    }
    static void  AutoSizeUp(List<GameObject> PoolType,Vector3 pos, Quaternion rot)
    {
        GameObject go = (GameObject)Instantiate(PoolType[0]);
        go.transform.parent = PoolType[0].GetComponent<PoolObj>().Original_Parent;
        go.name = PoolType[0].name;
        go.GetComponent<PoolObj>().Original_Parent = PoolType[0].GetComponent<PoolObj>().Original_Parent;
        go.transform.position = pos;
        go.transform.rotation = rot;
        PoolType.Add(go);
    }
}
cs

PoolObj


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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolObj : MonoBehaviour {
    public Transform Original_Parent;
    // Use this for initialization
    void Start () {
        
        
    }
    
    // Update is called once per frame
    void Update () {
        
    }
    public void UnActive()
    {
        this.transform.parent = Original_Parent;
        this.gameObject.SetActive(false);
    }
    public void UnActive_UI()
    {
        this.gameObject.SetActive(false);
    }
}
cs


사용 예제

PoolObj를 사용할 GameObj에 붙이고 해당 스크립트로

생성
GameObject go_PopUpBox = ObjectPoolManager.CreateObj(obj);

삭제
go_PopUpBox.GetComponent<PoolObj>().UnActive_UI();




미들웨어 엑조디아


DBConnectioninfo.sc

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
using System;
using System.Linq;
using System.Xml.Serialization;
namespace DBConnection
{
    
    //[Serializable]
    //[XmlRoot("Server")]
    //public class OracleConnectInfo
    //{
    //    [XmlElement("PORT")]
    //    public int Port { get; set; }
    //    [XmlElement("SID")]
    //    public string SID { get; set; }
    //    [XmlElement("USER")]
    //    public string USER { get; set; }
    //    [XmlElement("PW")]
    //    public string PASSWORD { get; set; }
       
    //}
    
    [Serializable]
    [XmlRoot("Server")]
    public class MssqlConnectionInfo
    {
        [XmlElement("IP")]
        public string IP { get; set; }
        [XmlElement("DATABASE")]
        public string DataBase { get; set; }
        [XmlElement("USER")]
        public string USER { get; set; }
        [XmlElement("PW")]
        public string PASSWORD { get; set; }
        [XmlElement("DATA_PORT")]
        public string DataPort { get; set; }
    }
    [Serializable]
    [XmlRoot("ServerData")]
    public class DataInfo
    {
        [XmlElement("item")]
        public XmlQuery[] xmlQuery;
        public XmlQuery ContainKey(string key)
        {
            try
            {
                var data = from xml in xmlQuery
                           where xml.KEY == key
                           select xml;
                return data.FirstOrDefault();
            }
            catch (System.Exception e)
            {
                Console.WriteLine("ERR : " + e.ToString());
                return null;
            }
        }
    }
    [Serializable]
    public class XmlQuery
    {
        [XmlElement("key")]
        public string KEY { get; set; }
        [XmlElement("query")]
        public string QUERY { get; set; }
        [XmlElement("param")]
        public string[] PARAM { get; set; }
        [XmlElement("type")]
        public string SENDTYPE { get; set; }
        [XmlElement("time")]
        public float TIME { get; set; }
    }
}
cs
##########################

Server



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Timers;
using System.IO;
using DBConnection;
using System.Data.SqlClient;
using System.Xml;
using System.Data;
namespace WebSocket
{
    public class Server
    {
        public static DataInfo dataQueryInfo;
        //private OracleClient oracleClient;
        private SqlConnection mssqlconn;
        private List<System.Timers.Timer> Timer = new List<System.Timers.Timer>();
        private readonly object lockObject = new object();
        public static byte[] SetDataFommat(string key, string value)
        {
            //data의 20byte는 Header 구분을 정의.
            byte[] header = new byte[20];
            byte[] strValue = Encoding.UTF8.GetBytes(value);
            byte[] result = new byte[header.Length + strValue.Length];
            strValue.CopyTo(result, header.Length);
            header = Encoding.UTF8.GetBytes(key);
            header.CopyTo(result, 0);
            return result;
        }
        public void StartServer()
        {
            try
            {
                Console.WriteLine("스타트 서버!!!");
                //Window 인증
                //string strConn = "Data Source=("+ Form1.ConnectionIP + ");Initial Catalog=TEST;Integrated Security=SSPI;";
                //SQL 인증
                string strConn = "Data Source=" + Form1.ConnectionIP + ",1433;Initial Catalog=" + Form1.mssqlconn.DataBase + ";User ID=" + Form1.mssqlconn.USER + ";Password=" + Form1.mssqlconn.PASSWORD + ";";
                mssqlconn = new SqlConnection(strConn);
                mssqlconn.Open();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataInfo));
                using (FileStream stream = new FileStream(Environment.CurrentDirectory + "\\" + "ServerData.xml", FileMode.Open, FileAccess.Read))
                {
                    dataQueryInfo = (DataInfo)xmlSerializer.Deserialize(stream);
                }
                //Console.WriteLine("Server Start Port : " + Form1.oracleConnectInfo.Data_Port);
                BroadCastTimerSettings();
            }
            catch (Exception e)
            {
                StopServer();
                Form1.instance.ErrorException(e, ErrorType.Connection);
            }
            /* 오라클 
            try
            {
                oracleClient = new OracleClient(Form1.ConnectionIP, Form1.oracleConnectInfo.Port, Form1.oracleConnectInfo.SID, Form1.oracleConnectInfo.USER, Form1.oracleConnectInfo.PASSWORD);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataInfo));
                using (FileStream stream = new FileStream(Environment.CurrentDirectory + "\\" + "ServerData.xml", FileMode.Open, FileAccess.Read))
                {
                    dataQueryInfo = (DataInfo)xmlSerializer.Deserialize(stream);
                }
                //Console.WriteLine("Server Start Port : " + Form1.oracleConnectInfo.Data_Port);
                BroadCastTimerSettings();
            }
            catch(Exception e)
            {
                StopServer();
                Form1.instance.ErrorException(e, ErrorType.Connection);
            }
            */
        }
        void BroadCastTimerSettings()
        {
            for (int i = 0; i < dataQueryInfo.xmlQuery.Length; i++)
            {
                if (dataQueryInfo.xmlQuery[i].SENDTYPE == "B")
                {
                    float r_time;
                    if (dataQueryInfo.xmlQuery[i]?.TIME == null || dataQueryInfo.xmlQuery[i].TIME == 0)
                        r_time = 1;
                    else
                        r_time = dataQueryInfo.xmlQuery[i].TIME;
                    System.Timers.Timer timer;
                    timer = new System.Timers.Timer(r_time * 1000);
                    XmlQuery xmlQuery = new XmlQuery();
                    xmlQuery = dataQueryInfo.xmlQuery[i];
                    timer.Elapsed += new ElapsedEventHandler((sender, e) => BroadCastSetData(sender, e, xmlQuery));
                    Timer.Add(timer);
                    timer.Enabled = true;
                }
            }
        }
        private void BroadCastSetData(Object source, ElapsedEventArgs e, XmlQuery xmlQuery)
        {
            if (Form1.ws.WebSocketServices.SessionCount < 1)
                return;
            
            
            lock (lockObject)
            {
                //오라클
                //string result = oracleClient.RequestQuery(xmlQuery.KEY, xmlQuery.QUERY);
                try
                {
                    DataSet ds = new DataSet(xmlQuery.KEY);
                    SqlDataAdapter rdr = new SqlDataAdapter(xmlQuery.QUERY, mssqlconn);
                    rdr.Fill(ds, "item");
                    string result = ds.GetXml();
                    byte[] strValue = SetDataFommat(xmlQuery.KEY, result);
                    //Console.Write("BType!!!");
                    //Console.WriteLine("strValue :" + strValue);
                    
                    Form1.ws.WebSocketServices.Broadcast(strValue);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(xmlQuery.KEY + "is Not Data");
                    Form1.instance.ErrorException(ex, ErrorType.Send);
                    return;
                }
            }
        }
        public void StopServer()
        {
            foreach (System.Timers.Timer t in Timer)
            {
                t.Enabled = false;
            }
            Timer.Clear();
            if (mssqlconn != null)
            {
                mssqlconn.Close();
                mssqlconn = null;
            }
            //if(oracleClient != null)
            //{
            //    oracleClient.DisConnect();
            //    oracleClient = null;
            //}
        }
    }
    
}
cs

##########################################
Form1



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
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using WebSocketSharp.Server;
using WebSocketSharp;
using System.Collections.Generic;
using DBConnection;
using System.Data.SqlClient;
using System.Xml;
using System.Data;
using System.Diagnostics;
namespace WebSocket
{
    public enum ErrorType {None, Connection, Receive, ClientSocket, Send};
    public partial class Form1 : Form
    {
        //public static OracleConnectInfo oracleConnectInfo;
        public static MssqlConnectionInfo mssqlconn;
        public static WebSocketServer ws;
        public static string ConnectionIP;
        public static string DataPort;
        public static int ConnectionPort;
        public static Form1 instance;
        public delegate void ConnectionEvent(string host, int usersCount);
        public delegate void ReceiveEvent(string key, string data, int TotalLen);
        public Server Server;
        private ErrorType ErrorType = ErrorType.None;
        private ErrorType Error
        {
            get { return ErrorType; }
            set
            {
                if(value == ErrorType.Connection)
                {
                    StopServer();
                }
                ErrorType = value;
            }
        }
        public Form1()
        {
            instance = this;
            InitializeComponent();
            //ConnectionIP = IpBox.Text;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(MssqlConnectionInfo));
            //Server 접속 정보 및 sql 접속정보 Xml 로드
            using (FileStream stream = new FileStream(Environment.CurrentDirectory + "\\" + "Server.xml", FileMode.Open, FileAccess.Read))
            {
                mssqlconn = (MssqlConnectionInfo)xmlSerializer.Deserialize(stream);
                xmlSerializer = new XmlSerializer(typeof(DataInfo));
            }
            ConnectionIP = mssqlconn.IP;
            DataPort = mssqlconn.DataPort;
            Server = new Server();
            ws = new WebSocketServer(IPAddress.Any, int.Parse(PortBox.Text));
            XmlSerializer xmlSerializer1 = new XmlSerializer(typeof(DataInfo));
            DataInfo dataQueryInfo;
            using (FileStream stream = new FileStream(Environment.CurrentDirectory + "\\" + "ServerData.xml", FileMode.Open, FileAccess.Read))
            {
                dataQueryInfo = (DataInfo)xmlSerializer1.Deserialize(stream);
            }
            //xml에 쿼리가 잘 읽혀졌는지 확인
            string[] a = { "kwon""dong""yu" };
            string k = string.Format(dataQueryInfo.xmlQuery[0].QUERY, a);
            //Console.WriteLine("TEST:"+k[0]);
            //Console.WriteLine("TEST:" + k);
        }
        
        private void Btn_Send_Click(object sender, EventArgs e)
        {
            if (TxBoxKey.Text == "")
                return;
            byte[] send_data = Server.SetDataFommat(TxBoxKey.Text, TxParam.Text);
            TxCount.Text = send_data.Length.ToString();
            ws.WebSocketServices.Broadcast(send_data);
        }
        private void Btn_Start_Click(object sender, EventArgs e)
        {
            ErrorType = ErrorType.None;
            if (IpBox.Text == "" || PortBox.Text == "")
            {
                Exception ex = new Exception("Please Input IP or Port");
                ErrorException(ex, ErrorType.None);
                return;
            }
            Server.StartServer();
            ws.AddWebSocketService<Client>("/Server");
            
            if (ErrorType == ErrorType.Connection)
                return;
            Btn_Start.Enabled = false;
            ws.Start();
        }
        private void Btn_Stop_Click(object sender, EventArgs e)
        {
            StopServer();
        }
        public void StopServer()
        {
            if (!ws.IsListening)
                return;
            Server.StopServer();
            ws.RemoveWebSocketService("/Server");
            ws.Stop();
            Btn_Start.Enabled = true;
            ClientIP.Clear();
        }
        public void ConnectID(string host,int userCount)
        {
            if(ClientIP.InvokeRequired && ClientCount.InvokeRequired)
            {
                var d = new ConnectionEvent(ConnectID);
                Invoke(d, new object[] { host, userCount });
            }
            else
            {
                if(!ClientIP.Text.Contains(host))
                    ClientIP.AppendText(host + Environment.NewLine);
                ClientCount.Text = userCount.ToString() ;
            }
        }
        public void DisConnectID(string host, int userCount)
        {
            if (ClientIP.InvokeRequired && ClientCount.InvokeRequired)
            {
                var d = new ConnectionEvent(DisConnectID);
                Invoke(d, new object[] {host, userCount });
            }
            else
            {
                ClientIP.Text = ClientIP.Text.Replace(host + Environment.NewLine, "");
                ClientCount.Text = userCount.ToString();
            }
        }
        public void ReceiveData(string key, string data, int TotalLen)
        {
            if(RxCount.InvokeRequired && RxBox.InvokeRequired)
            {
                var d = new ReceiveEvent(ReceiveData);
                Invoke(d, new object[] { key, data, TotalLen });
            }
            else
            {
                int tlen = 0;
                int.TryParse(RxCount.Text, out tlen);
                RxCount.Text = (tlen + TotalLen).ToString();
                RxBox.AppendText("[Received]" + Environment.NewLine);
                RxBox.AppendText("Key : " + key + Environment.NewLine);
                RxBox.AppendText("Data : " + data + Environment.NewLine);
            }
        }
        public void PythonTest(string key, string data, int TotalLen)
        {
            if (RxCount.InvokeRequired && RxBox.InvokeRequired)
            {
                var d = new ReceiveEvent(PythonTest);
                Invoke(d, new object[] { key, data, TotalLen });
            }
            else
            {
                int tlen = 0;
                int.TryParse(RxCount.Text, out tlen);
                RxCount.Text = (tlen + TotalLen).ToString();
                RxBox.AppendText("[PytonTest]" + Environment.NewLine);
                RxBox.AppendText("Key : " + key + Environment.NewLine);
                RxBox.AppendText("Data : " + data + Environment.NewLine);
                //가상환경 파이썬 exe를 직접 실행해서 파이썬 코드가 실행
                var psi = new ProcessStartInfo();
                string input_0 = "인자1"// 인자1
                string input_1 = "인자2"// 인자2
                string input_2 = "인자3"// 인자3
                psi.FileName = Application.StartupPath + "\\Python_3.6.5\\python.exe"//파이썬 가상환경 설치 경로
                psi.Arguments = Application.StartupPath + "./test.py "+input_0+" "+input_1+" "+input_2; //파일경로
                //3) Proecss configuration
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardError = true;
                //4) return value def
                var errors = ""// 출력은 하지 않습니다.
                var results = "";
                using (var process = Process.Start(psi))
                {
                    // process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputReceiver);
                    // process.BeginOutputReadLine();
                    // process.ErrorDataReceived += new DataReceivedEventHandler(StandardErrorReceiver);
                    // process.BeginErrorReadLine();
                    while (process.StandardOutput.Peek() > -1)
                    {
                        results = process.StandardOutput.ReadToEnd();
                    }
                    while (process.StandardError.Peek() > -1)
                    {
                        errors = process.StandardError.ReadToEnd();
                    }
                }
                RxBox.AppendText("Error : " + errors + Environment.NewLine);
                RxBox.AppendText("Result : " + results + Environment.NewLine);
            }
        }
        private void Btn_Clear_Click(object sender, EventArgs e)
        {
            RxBox.Clear();
            RxCount.Text = "0";
            TxCount.Text = "0";
            TxBoxKey.Clear();
            TxParam.Clear();
        }
        public void ErrorException(Exception exception, ErrorType error)
        {
            ErrorPopup errorPopup = new ErrorPopup();
            errorPopup.ErrorMessage(exception.Message);
            errorPopup.Show();
            Error = error;
            
        }
        private void IpBox_TextChanged(object sender, EventArgs e)
        {
            TextBox tb = sender as TextBox;
            ConnectionIP = tb.Text;
        }
        private void PortBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                TextBox tb = sender as TextBox;
                if(tb.Text != "")
                    ConnectionPort = int.Parse(tb.Text);
            }
            catch(Exception ex)
            {
                ErrorException(ex,ErrorType.Connection);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            IpBox.Text = ConnectionIP;
            PortBox.Text = DataPort;
            //try
            //{
            //    DataSet ds = new DataSet("KEY");
            //    string strConn = "Data Source=192.168.24.113,1433;Initial Catalog=TEST;User ID=sa;Password=1234;";
            //    using (SqlConnection SqlConnection = new SqlConnection(strConn))
            //    {
            //        SqlConnection.Open();
                   
            //        SqlDataAdapter rdr = new SqlDataAdapter("select * from TEST", SqlConnection);
            //        //xdr.MoveToContent();
            //        rdr.Fill(ds,"item");
            //        Console.WriteLine(ds.GetXml());
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("ERROR : " + ex.ToString());
            //}
        }
    }
    public class Client : WebSocketBehavior
    {
        //private OracleClient oracleClient;
        private SqlConnection SqlConnection;
        private string ConnIP = "";
        public Client()
        {
            //oracleClient = new OracleClient(Form1.ConnectionIP, Form1.oracleConnectInfo.Port, Form1.oracleConnectInfo.SID, Form1.oracleConnectInfo.USER, Form1.oracleConnectInfo.PASSWORD);
            string strConn = "Data Source=" + Form1.ConnectionIP + ",1433;Initial Catalog=" + Form1.mssqlconn.DataBase + ";User ID=" + Form1.mssqlconn.USER + ";Password=" + Form1.mssqlconn.PASSWORD + ";";
            SqlConnection = new SqlConnection(strConn);
        }
        protected override void OnError(WebSocketSharp.ErrorEventArgs e)
        {
            Form1.instance.ErrorException(e.Exception, ErrorType.ClientSocket);
        }
        protected override void OnOpen()
        {
            ConnIP = Context.UserEndPoint.Address.ToString();
            Form1.instance.ConnectID(Context.UserEndPoint.Address.ToString(), Sessions.Count);
        }
        protected override void OnClose(CloseEventArgs e)
        {
            Console.WriteLine("Disconnect : " + ConnIP);
            Form1.instance.DisConnectID(ConnIP, Sessions.Count);
        }
        //R 타잎 데이터 처리
        protected override void OnMessage(MessageEventArgs e)
        {
            //R 타잎 데이터 처리
            try
            {
                //Console.WriteLine("Data길이: "+ e.RawData.Length);
                
                byte[] header = new byte[20];
                byte[] conv_data = new byte[e.RawData.Length - header.Length];
                
                Array.Copy(e.RawData, header, 20);
                Array.Copy(e.RawData, header.Length, conv_data, 0, conv_data.Length);
                string key = Encoding.UTF8.GetString(header).Trim('\0');
                string value = Encoding.UTF8.GetString(conv_data).Trim('\0');
                //Console.WriteLine("Receive : " + key + " >>> value : " + value);
                Form1.instance.ReceiveData(key, value, e.RawData.Length);
                if (key == "pyton_Data_Req")
                {
                    Form1.instance.PythonTest(key, value, e.RawData.Length);
                }
                string[] param = value.Split(',');
                DataSet ds = new DataSet(key);
                if (key.ToUpper() == "INSERT" || key.ToUpper() == "UPDATE")
                {
                    //do codeing
                }
                else
                {
                    
                    XmlQuery query = Server.dataQueryInfo.ContainKey(key);
                    if (query == null)
                    {
                        Console.WriteLine(key + " : Key not found ! ");
                        return;
                    }
                    
                    string repQuery = string.Format(query.QUERY, param);
                    try
                    {
                        SqlConnection.Open();
                        SqlDataAdapter rdr = new SqlDataAdapter(repQuery, SqlConnection);
                        rdr.Fill(ds, "item");
                        SqlConnection.Close();
                        string result = ds.GetXml();
                        byte[] sendData = Server.SetDataFommat(key, result);
                        Send(sendData);
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                        SqlConnection.Close();
                        return;
                    }
                }
                //전송
                //Insert, Update는 클라인트가 oracle에 개별적으로 처리
                //if (key.ToUpper() == "INSERT" || key.ToUpper() == "UPDATE")
                //    oracleClient.EditCommandQuery(value);
                //else
                //{
                //    XmlQuery query = Server.dataQueryInfo.ContainKey(key);
                //    if (query == null)
                //    {
                //        Console.WriteLine(key + " : Key not found ! ");
                //        return;
                //    }
                //    string querybuff = query.QUERY;
                //    string oldStr = null;
                //    if (querybuff.Contains("%s"))
                //    {
                //        oldStr = "%s";
                //    }
                //    else if (querybuff.Contains("%S"))
                //    {
                //        oldStr = "%S";
                //    }
                //    else
                //    {
                //        Console.WriteLine("Query Warnnig! %s not found..");
                //        string NoEquls_result = oracleClient.RequestQuery(key, querybuff);
                //        if (NoEquls_result == null)
                //            return;
                //        byte[] bf = Server.SetDataFommat(key, NoEquls_result);
                //        Send(bf);
                //        return;
                //    }
                //    string sendQuery = querybuff.Replace(oldStr, "'" + value + "'");
                //    string result = oracleClient.RequestQuery(key, sendQuery);
                //    if (result == null)
                //        return;
                //    byte[] sendData = Server.SetDataFommat(key, result);
                //    Send(sendData);
                //}
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
               // Form1.instance.ErrorException(ex, ErrorType.Receive);
            }
        }
    }
}
cs
이 세개를 잘 조합하면 사용할수있습니다 그럼 20000

git rejected error(feat. cherry-pick)

 문제 아무 생각 없이 pull을 받지않고 로컬에서 작업! 커밋, 푸시 진행을 해버렷다. push에선 remote와 다르니 당연히 pull을 진행해라고 하지만 로컬에서 작업한 내용을 백업하지 않고 진행하기에는 부담스럽다(로컬작업 유실 가능성) 해결하려...