C# Socket 模擬http服務器幫助類


0x01 寫在前面

0x02 Http協議

0x03 TCP/IP

0x04 看代碼

0x05 總結

0x01 寫在前面

  由於工作中,經常需要在服務器之間,或者進程之間進行通信,分配任務等。用Socket操作,太麻煩了,需要建立連接,處理消息。所以

准備創建一個Socket模擬Http服務器的幫助類,來直接通過WebClient進行調用。

0x02 Http協議

我的理解:http協議,其實就是依托於tcp/ip的一個協議,也是可以通過socket發送消息,只是說。發送的內容格式滿足http的條件,就可以被理解成http協議。

常用Http頭。 Http版本也是可以寫成1.1的。

HTTP/1.0 200 OK
Content-Type: text/html
Connection: keep-alive
Content-Encoding: utf-8

0x03 TCP/IP

我的理解:TCP/IP協議其實是某一類協議的大分類了,很多協議都是基於這個協議來傳遞消息的。更詳細的信息,自己搜索一下。

0x04 看代碼

SocketHttpHelper.cs  socket模擬http幫助類

  1 public class SocketHttpHelper
  2 {
  3     private string ip = "127.0.0.1";
  4     private int port = 8123;
  5     private int count = 0;
  6     private Socket server = null;
  7 
  8     public string DefaultReturn = string.Empty;
  9 
 10     public event Func<string, string, string> Handler = null;
 11 
 12     public SocketHttpHelper()
 13     {
 14     }
 15 
 16     public SocketHttpHelper(string ip, int port)
 17     {
 18         this.ip = ip;
 19         this.port = port;
 20     }
 21 
 22     public void StartListen(int count = 10)
 23     {
 24         this.count = count;
 25         Thread t = new Thread(new ThreadStart(ProcessThread));
 26         t.IsBackground = true;
 27         t.Start();
 28     }
 29 
 30     public void CloseSocket()
 31     {
 32         try
 33         {
 34             server.Close();
 35         }
 36         catch { }
 37     }
 38 
 39     private void ProcessThread()
 40     {
 41         server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 42         server.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port));
 43         server.Listen(count);
 44         while (true)
 45         {
 46             try
 47             {
 48                 Socket client = server.Accept();
 49                 ThreadPool.QueueUserWorkItem(new WaitCallback(ListenExecute), client);
 50             }
 51             catch { }
 52             finally
 53             {
 54             }
 55         }
 56     }
 57 
 58     private void ListenExecute(object obj)
 59     {
 60         Socket client = obj as Socket;
 61         try
 62         {
 63             string ip = (client.RemoteEndPoint as System.Net.IPEndPoint).Address.ToString();
 64             byte[] buffer = new byte[1024];
 65             int count = client.Receive(buffer);
 66             if (count > 0)
 67             {
 68                 string content = Encoding.UTF8.GetString(buffer, 0, count);
 69 
 70                 // 解析 content
 71                 Regex actionRegex = new Regex(@"GET\s+/(?<action>\w+)\?(?<args>[^\s]{0,})");
 72                 string action = actionRegex.Match(content).Groups["action"].Value;
 73                 string args = actionRegex.Match(content).Groups["args"].Value;
 74                 string headStr = @"HTTP/1.0 200 OK
 75 Content-Type: text/html
 76 Connection: keep-alive
 77 Content-Encoding: utf-8
 78 
 79 ";
 80                 if (Handler != null)
 81                 {
 82                     try
 83                     {
 84                         string result = Handler(action, args);
 85                         string data = string.Format(headStr + result);
 86                         client.Send(Encoding.UTF8.GetBytes(data));
 87                     }
 88                     catch { }
 89                     finally
 90                     {
 91                     }
 92                 }
 93                 else
 94                 {
 95                     string data = string.Format(headStr + DefaultReturn);
 96                     client.Send(Encoding.UTF8.GetBytes(data));
 97                 }
 98             }
 99         }
100         catch { }
101         finally
102         {
103             try
104             {
105                 client.Shutdown(SocketShutdown.Both);
106                 client.Close();
107                 client.Dispose();
108             }
109             catch { }
110         }
111     }
112 }
View Code

0x05 總結

由於,每次都要從Socket開始寫,寫多了才發現,原來需要寫一個公用類,點都不費時間。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM