国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

C# 利用socekt做到http監(jiān)聽(tīng),怎么樣才能做到高性能

2019-11-17 02:27:04
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

C# 利用socekt做到http監(jiān)聽(tīng),怎么樣才能做到高性能

c#原始提供了http的監(jiān)聽(tīng)的類(lèi)HttpListener,實(shí)現(xiàn)了簡(jiǎn)單的http。文章地址《C# 控制臺(tái)或者winform程序開(kāi)啟http的監(jiān)聽(tīng)狀態(tài)》

但是經(jīng)過(guò)我測(cè)試,這個(gè)HttpListener提供的真的就只是簡(jiǎn)單的http監(jiān)聽(tīng)功能,無(wú)法實(shí)現(xiàn)高并發(fā)處理。

不知道是我處理問(wèn)題還是其他什么原因,無(wú)法實(shí)現(xiàn),當(dāng)上一個(gè)http請(qǐng)求連接尚未關(guān)閉的情況下,即便是把請(qǐng)求放到另外一個(gè)線程執(zhí)行,都要等到處理結(jié)束,close了才能接受和處理下一次的連接請(qǐng)求。

也許你會(huì)說(shuō)HttpListener不是提供了異步監(jiān)聽(tīng)的嘛?異步不就可以類(lèi)使用多線程實(shí)現(xiàn)嘛。但是經(jīng)過(guò)我測(cè)試,確實(shí)沒(méi)有得到我想要的實(shí)際效果。

所以另辟蹊徑。http其實(shí)質(zhì)就是socket的tcp封裝實(shí)現(xiàn)的功能,單次請(qǐng)求,處理,關(guān)閉的socket功能。

所以這里找到了可以使用最原始的socket的來(lái)提供http監(jiān)聽(tīng),處理數(shù)據(jù),關(guān)閉狀態(tài)。

好了直接上代碼,,一下代碼部分來(lái)至于博客園,園友帖子提供,時(shí)間久遠(yuǎn)亦不知道是哪位仁兄的帖子,見(jiàn)諒。

  1   internal class HttpServer  2     {  3         PRivate ipEndPoint _IP;  4         private TcpListener _Listeners;  5         private volatile bool IsInit = false;  6         HashSet<string> Names;  7   8         /// <summary>  9         /// 初始化服務(wù)器 10         /// </summary> 11         public HttpServer(string ip, int port, HashSet<string> names) 12         { 13             IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(ip), port); 14             this._IP = localEP; 15             Names = names; 16             if (Names == null) 17             { 18                 Names = new HashSet<string>(); 19             } 20             try 21             { 22                 foreach (var item in names) 23                 { 24                     Console.WriteLine(string.Format(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff:") + "Start Listen Http Socket -> {0}:{1}{2} ", ip, port, item)); 25                 } 26                 this._Listeners = new TcpListener(IPAddress.Parse(ip), port); 27                 this._Listeners.Start(5000); 28                 IsInit = true; 29                 this.AcceptAsync(); 30             } 31             catch (Exception ex) 32             { 33                 Console.WriteLine(ex); 34                 this.Dispose(); 35             } 36         } 37  38         private void AcceptAsync() 39         { 40             try 41             { 42                 this._Listeners.BeginAcceptTcpClient(new AsyncCallback(AcceptAsync_Async), null); 43             } 44             catch (Exception) { } 45         } 46  47         private void AcceptAsync_Async(IAsyncResult iar) 48         { 49             this.AcceptAsync(); 50             try 51             { 52                 TcpClient client = this._Listeners.EndAcceptTcpClient(iar); 53                 var socket = new HttpClient(client); 54                 Console.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff:") + "Create Http Socket Remote Socket LocalEndPoint:" + client.Client.LocalEndPoint + " RemoteEndPoint:" + client.Client.RemoteEndPoint.ToString()); 55                 foreach (var item in Names) 56                 { 57                     if (socket.http_url.StartsWith(item)) 58                     { 59                         try 60                         { 61                             socket.process(); 62                             return; 63                         } 64                         catch { break; } 65                     } 66                 } 67                 socket.WriteFailure(); 68                 socket.Close(); 69             } 70             catch (Exception) { } 71         } 72  73         /// <summary> 74         /// 釋放資源 75         /// </summary> 76         public void Dispose() 77         { 78             if (IsInit) 79             { 80                 IsInit = false; 81                 this.Dispose(true); 82                 GC.SuppressFinalize(this); 83             } 84         } 85  86         /// <summary> 87         /// 釋放所占用的資源 88         /// </summary> 89         /// <param name="flag1"></param> 90         protected virtual void Dispose([MarshalAs(UnmanagedType.U1)] bool flag1) 91         { 92             if (flag1) 93             { 94                 if (_Listeners != null) 95                 { 96                     try 97                     { 98                         Console.WriteLine(string.Format("Stop Http Listener -> {0}:{1} ", this.IP.Address.ToString(), this.IP.Port)); 99                         _Listeners.Stop();100                         _Listeners = null;101                     }102                     catch { }103                 }104             }105         }106 107         /// <summary>108         /// 獲取綁定終結(jié)點(diǎn)109         /// </summary>110         public IPEndPoint IP { get { return this._IP; } }111     }

這個(gè)是實(shí)現(xiàn)socket監(jiān)聽(tīng)狀態(tài)

  1  public class HttpClient  2     {  3         private static int MAX_POST_SIZE = 10 * 1024 * 1024; // 10MB  4         private const int BUF_SIZE = 4096;  5         private Stream inputStream;  6         public StreamWriter OutputStream;  7         public String http_method;  8         public String http_url;  9         public String http_protocol_versionstring; 10         public Hashtable httpHeaders = new Hashtable(); 11         internal TcpClient _Socket; 12  13         /// <summary> 14         /// 這個(gè)是服務(wù)器收到有效鏈接初始化 15         /// </summary> 16         internal HttpClient(TcpClient client) 17         { 18             this._Socket = client; 19             inputStream = new BufferedStream(_Socket.GetStream()); 20             OutputStream = new StreamWriter(new BufferedStream(_Socket.GetStream()), UTF8Encoding.Default); 21             ParseRequest(); 22         } 23  24         internal void process() 25         { 26             try 27             { 28                 if (http_method.Equals("GET")) 29                 { 30                     Program.Pool.ActiveHttp(this, GetRequestExec()); 31                 } 32                 else if (http_method.Equals("POST")) 33                 { 34                     Program.Pool.ActiveHttp(this, PostRequestExec()); 35                 } 36             } 37             catch (Exception e) 38             { 39                 Console.WriteLine("Exception: " + e.ToString()); 40                 WriteFailure(); 41             } 42         } 43  44         public void Close() 45         { 46             OutputStream.Flush(); 47             inputStream.Dispose(); 48             inputStream = null; 49             OutputStream.Dispose(); 50             OutputStream = null; // bs = null;             51             this._Socket.Close(); 52         } 53  54         #region 讀取流的一行 private string ReadLine() 55         /// <summary> 56         /// 讀取流的一行 57         /// </summary> 58         /// <returns></returns> 59         private string ReadLine() 60         { 61             int next_char; 62             string data = ""; 63             while (true) 64             { 65                 next_char = this.inputStream.ReadByte(); 66                 if (next_char == '/n') { break; } 67                 if (next_char == '/r') { continue; } 68                 if (next_char == -1) { Thread.Sleep(1); continue; }; 69                 data += Convert.ToChar(next_char); 70             } 71             return data; 72         } 73         #endregion 74  75         #region 轉(zhuǎn)化出 Request private void ParseRequest() 76         /// <summary> 77         /// 轉(zhuǎn)化出 Request 78         /// </summary> 79         private void ParseRequest() 80         { 81             String request = ReadLine(); 82             if (request != null) 83             { 84                 string[] tokens = request.Split(' '); 85                 if (tokens.Length != 3) 86                 { 87                     throw new Exception("invalid http request line"); 88                 } 89                 http_method = tokens[0].ToUpper(); 90                 http_url = tokens[1]; 91                 http_protocol_versionstring = tokens[2]; 92             } 93             String line; 94             while ((line = ReadLine()) != null) 95             { 96                 if (line.Equals("")) 97                 { 98                     break; 99                 }100                 int separator = line.IndexOf(':');101                 if (separator == -1)102                 {103                     throw new Exception("invalid http header line: " + line);104                 }105                 String name = line.Sub
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 高台县| 苗栗县| 祁连县| 舟曲县| 永清县| 东兰县| 垫江县| 嫩江县| 互助| 安多县| 定兴县| 湖州市| 昌黎县| 娄底市| 崇州市| 梅州市| 富民县| 旅游| 疏附县| 肃南| 芒康县| 曲阜市| 仙游县| 峡江县| 兴山县| 桐庐县| 云霄县| 巧家县| 金寨县| 紫阳县| 上高县| 滕州市| 昌黎县| 文化| 株洲市| 西畴县| 拉萨市| 高雄市| 天峨县| 河北省| 简阳市|