■ TcpListener 클래스에서 TCP 서버를 사용하는 방법을 보여준다.
[TestServer 프로젝트]
▶ MainForm.cs
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 |
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Windows.Forms; namespace TestServer { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// TCP 리스너 /// </summary> private TcpListener tcpListener; /// <summary> /// TCP 클라이언트 /// </summary> private TcpClient tcpClient; /// <summary> /// 네트워크 스트림 /// </summary> private NetworkStream networkStream; /// <summary> /// 스트림 라이터 /// </summary> private StreamWriter streamWriter; /// <summary> /// 서버 작업 여부 /// </summary> private bool isServerWorking = false; /// <summary> /// 스레드 /// </summary> private Thread thread; /// <summary> /// 트리플 DES 암호 서비스 공급자 /// </summary> private TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider(); /// <summary> /// 개인 키 바이트 배열 /// </summary> private byte[] privateKeyByteArray = new byte[] { 98 , 45 , 125, 56, 1 , 60 , 11, 38 , 123, 54 , 234, 9 , 76, 20 , 44, 7 , 12 , 223, 219, 95, 48, 156, 32, 239 }; /// <summary> /// 개인 키 초기 값 바이트 배열 /// </summary> private byte[] privateKeyInitialValueByteArray = new byte[] { 67, 12, 3, 41, 66, 78, 34, 123 }; /// <summary> /// 난수기 /// </summary> Random random = new Random(); /// <summary> /// 임의 값 /// </summary> private int randomValue = 0; /// <summary> /// 임의 개인 키 바이트 배열 /// </summary> private byte[] randomPrivateKeyByteArray = null; /// <summary> /// 임의 개인 키 초기 값 바이트 배열 /// </summary> private byte[] randomPrivateKeyInitialValueByteArray = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); #region 이벤트를 설정한다. this.Load += Form_Load; this.FormClosing += Form_FormClosing; this.sendButton.Click += sendButton_Click; this.timer.Tick += timer_Tick; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 폼 로드시 처리하기 - Form_Load(sender, e) /// <summary> /// 폼 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e"></param> private void Form_Load(object sender, EventArgs e) { this.isServerWorking = true; IPAddress ipAddress = new IPAddress(0); this.tcpListener = new TcpListener(ipAddress, 2014); this.tcpListener.Start(); this.thread = new Thread(StartServer); this.thread.Start(); this.timer.Enabled = true; this.randomValue = this.random.Next(1, 9); SetRandomPrivateKeyByteArray(this.randomValue); } #endregion #region 폼을 닫을 경우 처리하기 - Form_FormClosing(sender, e) /// <summary> /// 폼을 닫을 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_FormClosing(object sender, FormClosingEventArgs e) { if(!(this.streamWriter == null)) { try { this.streamWriter.WriteLine(Encrypt("서버를 종료합니다.")); this.streamWriter.Flush(); } catch { } } this.isServerWorking = false; this.timer.Enabled = false; if(!(this.streamWriter == null)) { this.streamWriter.Close(); } if(!(this.networkStream == null)) { this.networkStream.Close(); } if(!(this.tcpClient == null)) { this.tcpClient.Close(); } if(!(this.tcpListener == null)) { this.tcpListener.Stop(); } if(!(this.thread == null)) { this.thread.Abort(); } Application.ExitThread(); } #endregion #region 송신 버튼 클릭시 처리하기 - sendButton_Click(sender, e) /// <summary> /// 송신 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void sendButton_Click(object sender, EventArgs e) { if(this.networkStream != null && this.streamWriter != null) { this.streamWriter.WriteLine(Encrypt("12345abcde")); this.streamWriter.Flush(); } } #endregion #region 타이머 틱 처리하기 - timer_Tick(sender, e) /// <summary> /// 타이머 틱 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void timer_Tick(object sender, EventArgs e) { SendTimeMessage(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 임의 개인 키 바이트 배열 설정하기 - SetRandomPrivateKeyByteArray(randomValue) /// <summary> /// 임의 개인 키 바이트 배열 설정하기 /// </summary> /// <param name="randomValue">임의 값</param> private void SetRandomPrivateKeyByteArray(int randomValue) { randomPrivateKeyByteArray = new byte[this.privateKeyByteArray.Length]; randomPrivateKeyInitialValueByteArray = new byte[this.privateKeyInitialValueByteArray.Length]; for(int i = 0; i < this.privateKeyByteArray.Length; i++) { int value = (int)this.privateKeyByteArray[i]; randomPrivateKeyByteArray[i] = Convert.ToByte(value / randomValue); } for(int i = 0; i < this.privateKeyInitialValueByteArray.Length; i++) { int value = (int)this.privateKeyInitialValueByteArray[i]; randomPrivateKeyInitialValueByteArray[i] = Convert.ToByte(value / randomValue); } } #endregion #region 메시지 박스 데이터 추가하기 - AddMessageTextBoxData(text) /// <summary> /// 메시지 박스 데이터 추가하기 /// </summary> /// <param name="text">텍스트</param> private void AddMessageTextBoxData(string text) { this.messageTextBox.AppendText(text + "\r\n"); this.messageTextBox.Focus(); this.messageTextBox.ScrollToCaret(); } #endregion #region 서버 시작하기 - StartServer() /// <summary> /// 서버 시작하기 /// </summary> private void StartServer() { AddMessageTextBoxData("서버가 실행이 되었습니다."); while(this.isServerWorking) { try { this.tcpClient = this.tcpListener.AcceptTcpClient(); AddMessageTextBoxData("클라이언트가 접속하였습니다."); this.networkStream = this.tcpClient.GetStream(); this.streamWriter = new StreamWriter(this.networkStream); } catch { } } } #endregion #region 시간 메시지 송신하기 - SendTimeMessage() /// <summary> /// 시간 메시지 송신하기 /// </summary> private void SendTimeMessage() { try { string messageEncrypted = Encrypt(Convert.ToString(DateTime.Now)); this.streamWriter.WriteLine(messageEncrypted); this.streamWriter.Flush(); } catch { } } #endregion #region 암호화 하기 - Encrypt(message) /// <summary> /// 암호화 하기 /// </summary> /// <param name="message">메시지</param> /// <returns>암호화 메시지</returns> private string Encrypt(string message) { string messageEncrypted = null; byte[] textByteArray = UTF8Encoding.UTF8.GetBytes(message); messageEncrypted = Convert.ToBase64String ( this.tripleDESCryptoServiceProvider.CreateEncryptor ( randomPrivateKeyByteArray, randomPrivateKeyInitialValueByteArray ).TransformFinalBlock(textByteArray, 0, textByteArray.Length) ); textByteArray = UTF8Encoding.UTF8.GetBytes(this.randomValue.ToString() + messageEncrypted); messageEncrypted = Convert.ToBase64String ( this.tripleDESCryptoServiceProvider.CreateEncryptor ( this.privateKeyByteArray, this.privateKeyInitialValueByteArray ).TransformFinalBlock(textByteArray, 0, textByteArray.Length) ); return messageEncrypted; } #endregion } } |
[TestClient 프로젝트]
▶ MainForm.cs
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 |
using System; using System.IO; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Windows.Forms; namespace TestClient { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// TCP 클라이언트 /// </summary> private TcpClient tcpClient; /// <summary> /// 네트워크 스트림 /// </summary> private NetworkStream networkStream; /// <summary> /// 스트림 리더 /// </summary> private StreamReader streamReader; /// <summary> /// 스레드 /// </summary> private Thread thread; /// <summary> /// 트리플 DES 암호 서비스 공급자 /// </summary> private TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider(); /// <summary> /// 개인 키 바이트 배열 /// </summary> private byte[] privateKeyByteArray = new byte[] { 98 , 45 , 125, 56, 1 , 60 , 11, 38 , 123, 54 , 234, 9 , 76, 20 , 44, 7 , 12 , 223, 219, 95, 48, 156, 32, 239 }; /// <summary> /// 개인 키 초기 값 바이트 배열 /// </summary> private byte[] privateKeyInitialValueByteArray = new byte[] { 67, 12, 3, 41, 66, 78, 34, 123 }; /// <summary> /// 임의 개인 키 바이트 배열 /// </summary> private byte[] randomPrivateKeyByteArray = null; /// <summary> /// 임의 개인 키 초기 값 바이트 배열 /// </summary> private byte[] randomPrivateKeyInitialValueByteArray = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); #region 이벤트를 설정한다. Load += Form_Load; FormClosing += Form_FormClosing; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 폼 로드시 처리하기 - Form_Load(sender, e) /// <summary> /// 폼 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_Load(object sender, EventArgs e) { try { this.tcpClient = new TcpClient("127.0.0.1", 2014); AddMessageTextBoxData("서버에 접속 했습니다."); this.networkStream = this.tcpClient.GetStream(); this.streamReader = new StreamReader(this.networkStream); this.thread = new Thread(ReceiveMessage); this.thread.Start(); } catch { AddMessageTextBoxData("서버에 접속하지 못 했습니다."); } } #endregion #region 폼을 닫을 경우 처리하기 - Form_FormClosing(sender, e) /// <summary> /// 폼을 닫을 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_FormClosing(object sender, FormClosingEventArgs e) { try { if(!(this.streamReader == null)) { this.streamReader.Close(); } if(!(this.networkStream == null)) { this.networkStream.Close(); } if(!(this.tcpClient == null)) { this.tcpClient.Close(); } if(!(this.thread == null)) { this.thread.Abort(); } } catch { return; } Application.ExitThread(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 메시지 텍스트 박스 데이터 추가하기 - AddMessageTextBoxData(text) /// <summary> /// 메시지 텍스트 박스 데이터 추가하기 /// </summary> /// <param name="text">텍스트</param> private void AddMessageTextBoxData(string text) { this.messageTextBox.AppendText(text + "\r\n"); this.messageTextBox.Focus(); this.messageTextBox.ScrollToCaret(); } #endregion #region 임의 개인 키 바이트 배열 설정하기 - SetRandomPrivateKeyByteArray(randomValue) /// <summary> /// 임의 개인 키 바이트 배열 설정하기 /// </summary> /// <param name="randomValue">임의 값</param> private void SetRandomPrivateKeyByteArray(int randomValue) { this.randomPrivateKeyByteArray = new byte[this.privateKeyByteArray.Length]; this.randomPrivateKeyInitialValueByteArray = new byte[this.privateKeyInitialValueByteArray.Length]; for(int i = 0; i < this.privateKeyByteArray.Length; i++) { int value = (int)this.privateKeyByteArray[i]; this.randomPrivateKeyByteArray[i] = Convert.ToByte(value / randomValue); } for(int i = 0; i < this.privateKeyInitialValueByteArray.Length; i++) { int value = (int)this.privateKeyInitialValueByteArray[i]; this.randomPrivateKeyInitialValueByteArray[i] = Convert.ToByte(value / randomValue); } } #endregion #region 암호화 풀기 - Decrypt(messageEncrypted) /// <summary> /// 암호화 풀기 /// </summary> /// <param name="messageEncrypted">암호화 메시지</param> /// <returns>메시지</returns> private string Decrypt(string messageEncrypted) { string message = null; byte[] messageEncryptedByteArrat = Convert.FromBase64String(messageEncrypted); message = UTF8Encoding.UTF8.GetString ( this.tripleDESCryptoServiceProvider.CreateDecryptor ( this.privateKeyByteArray, this.privateKeyInitialValueByteArray ).TransformFinalBlock(messageEncryptedByteArrat, 0, messageEncryptedByteArrat.Length) ); SetRandomPrivateKeyByteArray(Convert.ToInt32(message.Substring(0, 1))); messageEncryptedByteArrat = Convert.FromBase64String(message.Substring(1, message.Length - 1)); message = UTF8Encoding.UTF8.GetString ( this.tripleDESCryptoServiceProvider.CreateDecryptor ( this.randomPrivateKeyByteArray, this.randomPrivateKeyInitialValueByteArray ).TransformFinalBlock(messageEncryptedByteArrat, 0, messageEncryptedByteArrat.Length) ); return message; } #endregion #region 메시지 수신하기 - ReceiveMessage() /// <summary> /// 메시지 수신하기 /// </summary> private void ReceiveMessage() { try { while(true) { if(this.networkStream.CanRead) { string messageEncrypted = this.streamReader.ReadLine(); if(messageEncrypted.Length > 0) { string message = Decrypt(messageEncrypted); AddMessageTextBoxData(message); } } } } catch { } } #endregion } } |