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开始写,写多了才发现,原来需要写一个公用类,点都不费时间。

posted @ 2016-05-22 21:54  Supper_litt  阅读(2441)  评论(2编辑  收藏  举报