티스토리 뷰

======================================================

 안녕하세요 Doridori 입니다.

 정말 바쁘기도 하고(이건 계속 바쁜 것 같은데 어쨌든 일을 하면서 준비하려고 하니 시간도 쉽지 않고 업무량도 많고 하고 싶은것도 많고 그래서 그런듯 합니다. ㅎㅎ), 도도하다 쪽을 집중하다 보니 거의 5개월 만에 C# 강의를 올리게 되었습니다. 

 C# 강의. 68강을 올릴 때 다음 프로젝트를 준비 하고 있다고 작성 하였는데, 벌써 계절도 지나고 그 준비 한다고 했던 프로젝트도 끝나고 그 다음 프로젝트를 진행 하고 있습니다. 

 그 사이에 코로나도 걸리고 독감도 걸리고... ㅎㅎ 

 엄청 오랫동안 아무것도 안한것 같지만 도도하다의 경우 꾸준하게 업로드 하고 있습니다. 

 그 사이에 doridori 아이콘도 만들어서 올리고, SQLD 자격증도 취득하고, 교육도 다녀오고... 

 생각해보면 바쁘면서도 알차게 보내고 있긴 하네요. 

 또 열심히 달려보도록 하겠습니다.

 모두 화이팅 하십시오!!

======================================================

 

69. Rest API (Server Program)

Source UI)

69. Rest API (Server Program) (UI).zip
0.06MB

Soruce 전체)

69. Rest API (Server Program).zip
0.06MB

교재)

69. Rest API (Server Program).pdf
0.23MB

 

 아무래도 웹쪽을 하다 보니 Rest API를 많이 이야기 하였는데 그래서 예전부터 Rest API에 대해 업로드 하려고 자료를 준비하고 있었습니다. 

 헌데 생각보다 예제가 마음에 들게 나오지 않아서 업로드를 하고 있지 않았다가 이번에 회사 업무중 sample로 비슷한 프로그램을 만들게 되어 조금 더 간략하게 준비 해보았습니다.

 Rest API의 경우 결국 본질은 통신 규약이기 때문에 대략 적인 형태만 알고 있으면 되지 않을까 싶고 뼈대나 이론적인 부분만 알고 있으면 활용하는 것에는 크게 지장이 없다 정도로 생각 됩니다. 

 

UI)

 간단한 통신이 가능 한 간단한 Server Program으로 구성 하였으며 Client Program도 함께 넣어 놓으려고 준비하고 있었는데 그럼 한 Program에서 동작하는 느낌이 날것 같아서 그냥 프로그램을 따로 만들어야 겠다 라고 생각하고 만들고 있습니다. 

 테스트를 해야 하는 Client를 만들어 놓지 않은 상황이라 구글에서 Rest API Online Test으로 검색해서 테스트를 할까 싶어서 이것저것 찾아 보았는데 Method Type 기준으로 임의로 프로그램 제한을 둔 사이트 들도 있어서 고민을 하다가, 크롬 확장 프로그램인 Talent API Tester로 올리기로 하였습니다. 

 Post Man이라는 프로그램도 많이 사용한다고 하는데 간단하게 테스트만 할 예정이라 기본 구성만 되면 되지 않을까 생각 합니다. 

강의)

Source)

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
 
namespace RestAPI_Server
{
    public partial class Form1 : Form
    {
        // enum Type
        enum HttpMethodType
        {
            POST,
            GET,
            PUT,
            DELETE
        }
 
        HttpListener httpListener;
 
        /// <summary>
        /// Program 진입점
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
 
 
        /// <summary>
        /// prefixes 기준 Server Start
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            // httpListener가 null 일 경우 초기화 및 Prefixes 설정
            if (httpListener == null)
            {
                httpListener = new HttpListener();
                httpListener.Prefixes.Add(tboxURL.Text);
            }
 
            if (!httpListener.IsListening)
            {
                httpListener.Start();  // httpListener Start
                Log(enLogLevel.Info_L1, $@"RestAPI Server is Started. URL : {tboxURL.Text}");
 
                //비동기 task 생성
                Task.Factory.StartNew(() =>
                {
                    // httpListener가 유효 한지 확인
                    while (httpListener != null)
                    {
                        try
                        {
                            if (!httpListener.IsListening) break;  // Server가 수신 대기 상태가 아닐 경우 while를 빠져 나감
 
                            HttpListenerContext context = this.httpListener.GetContext();   // Client의 요청을 수신
 
                            // Client 요청에서 HTTP Method와 URL을 추출
                            string httpmethod = context.Request.HttpMethod;
                            string rawurl = context.Request.RawUrl;
 
                            // Httpmethod 값이 HttpMethodType에 있는 값인지 확인
                            if (!Enum.IsDefined(typeof(HttpMethodType), httpmethod)) continue;
 
                            string text;
                            var request = context.Request;   // 본문의 Data를 Read
                            using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
                            {
                                text = reader.ReadToEnd();
                            }
 
                            this.Invoke(new Action(delegate ()
                            {
                                tboxHttpMethod.Text = httpmethod;
                                tboxRawURL.Text = rawurl;
                            }));
 
                            string result = "";
                            //result += string.Format("httpmethod = {0}\r\n", httpmethod);
                            result += string.Format("url = {0}, ", rawurl);
 
                            result += string.Format("body= {0}", text);
 
                            Log(enLogLevel.Info_L1, result);  // Log Display
 
                            context.Response.Close();  // Client에 응답을 보내고 연결을 닫음
                        }
                        catch
                        {
                            Log(enLogLevel.Error, "Exception");
                        }
                    }
                });
            }
 
            btnStatus(sender);
        }
 
 
        /// <summary>
        /// Server Stop
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            // httpListener Resource 해제
            if (httpListener != null)
            {
                httpListener.Stop();
                httpListener.Close();
                httpListener = null;
                Log(enLogLevel.Info_L1, $@"RestAPI Server is Stop.");
 
                btnStatus(sender);
            }
        }
 
 
        /// <summary>
        /// Button에 대한 Enable 상태 관리
        /// </summary>
        /// <param name="btnObject"></param>
        private void btnStatus(object btnObject)
        {
            System.Windows.Forms.Button btn = (System.Windows.Forms.Button)btnObject;
 
            switch (btn.Name)
            {
                case "btnStart":
                    btnStart.Enabled = false;
                    btnStop.Enabled = true;
                    break;
                case "btnStop":
                    btnStart.Enabled = true;
                    btnStop.Enabled = false;
                    break;
            }
        }
 
 
        #region Log Viewer  (기존 Source 재활용)
 
        // Log Level을 지정 할 Enum (44강 Tree View 참조)
        enum enLogLevel
        {
            Info_L1,
            Info_L2,
            Info_L3,
            Warning,
            Error,
        }
 
        private void Log(enLogLevel eLevel, string LogDesc)
        {
            this.Invoke(new Action(delegate ()
            {
                DateTime dTime = DateTime.Now;
                string LogInfo = $"{dTime:yyyy-MM-dd hh:mm:ss.fff} [{eLevel.ToString()}] {LogDesc}";
                lboxLog.Items.Insert(0, LogInfo);
            }));
        }
 
        private void Log(DateTime dTime, enLogLevel eLevel, string LogDesc)
        {
            this.Invoke(new Action(delegate ()
            {
                string LogInfo = $"{dTime:yyyy-MM-dd hh:mm:ss.fff} [{eLevel.ToString()}] {LogDesc}";
                lboxLog.Items.Insert(0, LogInfo);
            }));
        }
 
 
 
        #endregion
 
 
    }
}
cs
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함