C#編寫高性能網絡服務器(源碼)


最近有項目要做一個高性能網絡服務器,決定下功夫搞定完成端口(IOCP),最終花了一個星期終於把它弄清楚了,並用C++寫了一個版本,效率很不錯。

但,從項目的總體需求來考慮,最終決定上.net平台,因此又花了一天一夜弄出了一個C#版,在這與大家分享。

一些心得體會:

1、在C#中,不用去面對完成端口的操作系統內核對象,Microsoft已經為我們提供了SocketAsyncEventArgs類,它封裝了IOCP的使用。請參考:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socketasynceventargs.aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-1

2、我的SocketAsyncEventArgsPool類使用List對象來存儲對客戶端來通信的SocketAsyncEventArgs對象,它相當於直接使用內核對象時的IoContext。我這樣設計比用堆棧來實現的好處理是,我可以在SocketAsyncEventArgsPool池中找到任何一個與服務器連接的客戶,主動向它發信息。而用堆棧來實現的話,要主動給客戶發信息,則還要設計一個結構來存儲已連接上服務器的客戶。

3、對每一個客戶端不管還發送還是接收,我使用同一個SocketAsyncEventArgs對象,對每一個客戶端來說,通信是同步進行的,也就是說服務器高度保證同一個客戶連接上要么在投遞發送請求,並等待;或者是在投遞接收請求,等待中。本例只做echo服務器,還未考慮由服務器主動向客戶發送信息。

4、SocketAsyncEventArgs的UserToken被直接設定為被接受的客戶端Socket。

5、沒有使用BufferManager 類,因為我在初始化時給每一個SocketAsyncEventArgsPool中的對象分配一個緩沖區,發送時使用Arrary.Copy來進行字符拷貝,不去改變緩沖區的位置,只改變使用的長度,因此在下次投遞接收請求時恢復緩沖區長度就可以了!如果要主動給客戶發信息的話,可以new一個SocketAsyncEventArgs對象,或者在初始化中建立幾個來專門用於主動發送信息,因為這種需求一般是進行信息群發,建立一個對象可以用於很多次信息發送,總體來看,這種花銷不大,還減去了字符拷貝和消耗。

6、測試結果:(在我的筆記本上時行的,我的本本是T420 I7 8G內存)

100客戶 100,000(十萬次)不間斷的發送接收數據(發送和接收之間沒有Sleep,就一個一循環,不斷的發送與接收)
耗時3004.6325 秒完成
總共 10,000,000 一千萬次訪問
平均每分完成 199,691.6 次發送與接收
平均每秒完成 3,328.2 次發送與接收

整個運行過程中,內存消耗在開始兩三分種后就保持穩定不再增漲。

看了一下對每個客戶端的延遲最多不超過2毫秒,CPU占用在8%左右。

7、下載地址:http://download.csdn.net/detail/ztk12/4928644

8、源碼:

IoContextPool.cs
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.Net.Sockets;
 5 
 6 namespace IocpServer
 7 {
 8     /// <summary>
 9     /// 與每個客戶Socket相關聯,進行Send和Receive投遞時所需要的參數
10     /// </summary>
11     internal sealed class IoContextPool
12     {
13         List<SocketAsyncEventArgs> pool;        //為每一個Socket客戶端分配一個SocketAsyncEventArgs,用一個List管理,在程序啟動時建立。
14         Int32 capacity;                         //pool對象池的容量
15         Int32 boundary;                         //已分配和未分配對象的邊界,大的是已經分配的,小的是未分配的
16 
17         internal IoContextPool(Int32 capacity)
18         {
19             this.pool = new List<SocketAsyncEventArgs>(capacity);
20             this.boundary = 0;
21             this.capacity = capacity;
22         }
23 
24         /// <summary>
25         /// 往pool對象池中增加新建立的對象,因為這個程序在啟動時會建立好所有對象,
26         /// 故這個方法只在初始化時會被調用,因此,沒有加鎖。
27         /// </summary>
28         /// <param name="arg"></param>
29         /// <returns></returns>
30         internal bool Add(SocketAsyncEventArgs arg)
31         {
32             if (arg != null && pool.Count < capacity)
33             {
34                 pool.Add(arg);
35                 boundary++;
36                 return true;
37             }
38             else
39                 return false;
40         }
41 
42         /// <summary>
43         /// 取出集合中指定對象,內部使用
44         /// </summary>
45         /// <param name="index"></param>
46         /// <returns></returns>
47         //internal SocketAsyncEventArgs Get(int index)
48         //{
49         //    if (index >= 0 && index < capacity)
50         //        return pool[index];
51         //    else
52         //        return null;
53         //}
54 
55         /// <summary>
56         /// 從對象池中取出一個對象,交給一個socket來進行投遞請求操作
57         /// </summary>
58         /// <returns></returns>
59         internal SocketAsyncEventArgs Pop()
60         {
61             lock (this.pool)
62             {
63                 if (boundary > 0)
64                 {
65                     --boundary;
66                     return pool[boundary];
67                 }
68                 else
69                     return null;
70             }
71         }
72 
73         /// <summary>
74         /// 一個socket客戶斷開,與其相關的IoContext被釋放,重新投入Pool中,備用。
75         /// </summary>
76         /// <param name="arg"></param>
77         /// <returns></returns>
78         internal bool Push(SocketAsyncEventArgs arg)
79         {
80             if (arg != null)
81             {
82                 lock (this.pool)
83                 {
84                     int index = this.pool.IndexOf(arg, boundary);  //找出被斷開的客戶,此處一定能查到,因此index不可能為-1,必定要大於0。
85                     if (index == boundary)         //正好是邊界元素
86                         boundary++;
87                     else
88                     {
89                         this.pool[index] = this.pool[boundary];     //將斷開客戶移到邊界上,邊界右移
90                         this.pool[boundary++] = arg;
91                     }
92                 }
93                 return true;
94             }
95             else
96                 return false;
97         }
98     }
99 }
IoServer.cs
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using System.Net.Sockets;
  5 using System.Threading;
  6 using System.Net;
  7 
  8 namespace IocpServer
  9 {
 10     /// <summary>
 11     /// 基於SocketAsyncEventArgs 實現 IOCP 服務器
 12     /// </summary>
 13     internal sealed class IoServer
 14     {
 15         /// <summary>
 16         /// 監聽Socket,用於接受客戶端的連接請求
 17         /// </summary>
 18         private Socket listenSocket;
 19 
 20         /// <summary>
 21         /// 用於服務器執行的互斥同步對象
 22         /// </summary>
 23         private static Mutex mutex = new Mutex();
 24 
 25         /// <summary>
 26         /// 用於每個I/O Socket操作的緩沖區大小
 27         /// </summary>
 28         private Int32 bufferSize;
 29 
 30         /// <summary>
 31         /// 服務器上連接的客戶端總數
 32         /// </summary>
 33         private Int32 numConnectedSockets;
 34 
 35         /// <summary>
 36         /// 服務器能接受的最大連接數量
 37         /// </summary>
 38         private Int32 numConnections;
 39 
 40         /// <summary>
 41         /// 完成端口上進行投遞所用的IoContext對象池
 42         /// </summary>
 43         private IoContextPool ioContextPool;
 44 
 45         public MainForm mainForm;
 46 
 47         /// <summary>
 48         /// 構造函數,建立一個未初始化的服務器實例
 49         /// </summary>
 50         /// <param name="numConnections">服務器的最大連接數據</param>
 51         /// <param name="bufferSize"></param>
 52         internal IoServer(Int32 numConnections, Int32 bufferSize)
 53         {
 54             this.numConnectedSockets = 0;
 55             this.numConnections = numConnections;
 56             this.bufferSize = bufferSize;
 57 
 58             this.ioContextPool = new IoContextPool(numConnections);
 59 
 60             // 為IoContextPool預分配SocketAsyncEventArgs對象
 61             for (Int32 i = 0; i < this.numConnections; i++)
 62             {
 63                 SocketAsyncEventArgs ioContext = new SocketAsyncEventArgs();
 64                 ioContext.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted);
 65                 ioContext.SetBuffer(new Byte[this.bufferSize], 0, this.bufferSize);
 66 
 67                 // 將預分配的對象加入SocketAsyncEventArgs對象池中
 68                 this.ioContextPool.Add(ioContext);
 69             }
 70         }
 71 
 72         /// <summary>
 73         /// 當Socket上的發送或接收請求被完成時,調用此函數
 74         /// </summary>
 75         /// <param name="sender">激發事件的對象</param>
 76         /// <param name="e">與發送或接收完成操作相關聯的SocketAsyncEventArg對象</param>
 77         private void OnIOCompleted(object sender, SocketAsyncEventArgs e)
 78         {
 79             // Determine which type of operation just completed and call the associated handler.
 80             switch (e.LastOperation)
 81             {
 82                 case SocketAsyncOperation.Receive:
 83                     this.ProcessReceive(e);
 84                     break;
 85                 case SocketAsyncOperation.Send:
 86                     this.ProcessSend(e);
 87                     break;
 88                 default:
 89                     throw new ArgumentException("The last operation completed on the socket was not a receive or send");
 90             }
 91         }
 92 
 93         /// <summary>
 94         ///接收完成時處理函數
 95         /// </summary>
 96         /// <param name="e">與接收完成操作相關聯的SocketAsyncEventArg對象</param>
 97         private void ProcessReceive(SocketAsyncEventArgs e)
 98         {
 99             // 檢查遠程主機是否關閉連接
100             if (e.BytesTransferred > 0)
101             {
102                 if (e.SocketError == SocketError.Success)
103                 {
104                     Socket s = (Socket)e.UserToken;
105                     //判斷所有需接收的數據是否已經完成
106                     if (s.Available == 0)
107                     {
108                         // 設置發送數據
109                         Array.Copy(e.Buffer, 0, e.Buffer, e.BytesTransferred, e.BytesTransferred);
110                         e.SetBuffer(e.Offset, e.BytesTransferred * 2);
111                         if (!s.SendAsync(e))        //投遞發送請求,這個函數有可能同步發送出去,這時返回false,並且不會引發SocketAsyncEventArgs.Completed事件
112                         {
113                             // 同步發送時處理發送完成事件
114                             this.ProcessSend(e);
115                         }
116                     }
117                     else if (!s.ReceiveAsync(e))    //為接收下一段數據,投遞接收請求,這個函數有可能同步完成,這時返回false,並且不會引發SocketAsyncEventArgs.Completed事件
118                     {
119                         // 同步接收時處理接收完成事件
120                         this.ProcessReceive(e);
121                     }
122                 }
123                 else
124                 {
125                     this.ProcessError(e);
126                 }
127             }
128             else
129             {
130                 this.CloseClientSocket(e);
131             }
132         }
133 
134         /// <summary>
135         /// 發送完成時處理函數
136         /// </summary>
137         /// <param name="e">與發送完成操作相關聯的SocketAsyncEventArg對象</param>
138         private void ProcessSend(SocketAsyncEventArgs e)
139         {
140             if (e.SocketError == SocketError.Success)
141             {
142                 Socket s = (Socket)e.UserToken;
143 
144                 //接收時根據接收的字節數收縮了緩沖區的大小,因此投遞接收請求時,恢復緩沖區大小
145                 e.SetBuffer(0, bufferSize);
146                 if (!s.ReceiveAsync(e))     //投遞接收請求
147                 {
148                     // 同步接收時處理接收完成事件
149                     this.ProcessReceive(e);
150                 }
151             }
152             else
153             {
154                 this.ProcessError(e);
155             }
156         }
157 
158         /// <summary>
159         /// 處理socket錯誤
160         /// </summary>
161         /// <param name="e"></param>
162         private void ProcessError(SocketAsyncEventArgs e)
163         {
164             Socket s = e.UserToken as Socket;
165             IPEndPoint localEp = s.LocalEndPoint as IPEndPoint;
166 
167             this.CloseClientSocket(s, e);
168 
169             string outStr = String.Format("套接字錯誤 {0}, IP {1}, 操作 {2}。", (Int32)e.SocketError, localEp, e.LastOperation);
170             mainForm.Invoke(mainForm.setlistboxcallback, outStr);
171             //Console.WriteLine("Socket error {0} on endpoint {1} during {2}.", (Int32)e.SocketError, localEp, e.LastOperation);
172         }
173 
174         /// <summary>
175         /// 關閉socket連接
176         /// </summary>
177         /// <param name="e">SocketAsyncEventArg associated with the completed send/receive operation.</param>
178         private void CloseClientSocket(SocketAsyncEventArgs e)
179         {
180             Socket s = e.UserToken as Socket;
181             this.CloseClientSocket(s, e);
182         }
183 
184         private void CloseClientSocket(Socket s, SocketAsyncEventArgs e)
185         {
186             Interlocked.Decrement(ref this.numConnectedSockets);
187 
188             // SocketAsyncEventArg 對象被釋放,壓入可重用隊列。
189             this.ioContextPool.Push(e);            
190             string outStr = String.Format("客戶 {0} 斷開, 共有 {1} 個連接。", s.RemoteEndPoint.ToString(), this.numConnectedSockets);
191             mainForm.Invoke(mainForm.setlistboxcallback, outStr);            
192             //Console.WriteLine("A client has been disconnected from the server. There are {0} clients connected to the server", this.numConnectedSockets);
193             try
194             {
195                 s.Shutdown(SocketShutdown.Send);
196             }
197             catch (Exception)
198             {
199                 // Throw if client has closed, so it is not necessary to catch.
200             }
201             finally
202             {
203                 s.Close();
204             }
205         }
206 
207         /// <summary>
208         /// accept 操作完成時回調函數
209         /// </summary>
210         /// <param name="sender">Object who raised the event.</param>
211         /// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
212         private void OnAcceptCompleted(object sender, SocketAsyncEventArgs e)
213         {
214             this.ProcessAccept(e);
215         }
216 
217         /// <summary>
218         /// 監聽Socket接受處理
219         /// </summary>
220         /// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
221         private void ProcessAccept(SocketAsyncEventArgs e)
222         {
223             Socket s = e.AcceptSocket;
224             if (s.Connected)
225             {
226                 try
227                 {
228                     SocketAsyncEventArgs ioContext = this.ioContextPool.Pop();
229                     if (ioContext != null)
230                     {
231                         // 從接受的客戶端連接中取數據配置ioContext
232 
233                         ioContext.UserToken = s;
234 
235                         Interlocked.Increment(ref this.numConnectedSockets);
236                         string outStr = String.Format("客戶 {0} 連入, 共有 {1} 個連接。",  s.RemoteEndPoint.ToString(),this.numConnectedSockets);
237                         mainForm.Invoke(mainForm.setlistboxcallback,outStr);
238                         //Console.WriteLine("Client connection accepted. There are {0} clients connected to the server",
239                             //this.numConnectedSockets);
240 
241                         if (!s.ReceiveAsync(ioContext))
242                         {
243                             this.ProcessReceive(ioContext);
244                         }
245                     }
246                     else        //已經達到最大客戶連接數量,在這接受連接,發送“連接已經達到最大數”,然后斷開連接
247                     {
248                         s.Send(Encoding.Default.GetBytes("連接已經達到最大數!"));
249                         string outStr = String.Format("連接已滿,拒絕 {0} 的連接。", s.RemoteEndPoint);
250                         mainForm.Invoke(mainForm.setlistboxcallback, outStr);
251                         s.Close();
252                    }
253                 }
254                 catch (SocketException ex)
255                 {
256                     Socket token = e.UserToken as Socket;
257                     string outStr = String.Format("接收客戶 {0} 數據出錯, 異常信息: {1} 。", token.RemoteEndPoint, ex.ToString());
258                     mainForm.Invoke(mainForm.setlistboxcallback, outStr);
259                     //Console.WriteLine("Error when processing data received from {0}:\r\n{1}", token.RemoteEndPoint, ex.ToString());
260                 }
261                 catch (Exception ex)
262                 {
263                     mainForm.Invoke(mainForm.setlistboxcallback, "異常:" + ex.ToString());
264                 }
265                 // 投遞下一個接受請求
266                 this.StartAccept(e);
267             }
268         }
269 
270         /// <summary>
271         /// 從客戶端開始接受一個連接操作
272         /// </summary>
273         /// <param name="acceptEventArg">The context object to use when issuing 
274         /// the accept operation on the server's listening socket.</param>
275         private void StartAccept(SocketAsyncEventArgs acceptEventArg)
276         {
277             if (acceptEventArg == null)
278             {
279                 acceptEventArg = new SocketAsyncEventArgs();
280                 acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted);
281             }
282             else
283             {
284                 // 重用前進行對象清理
285                 acceptEventArg.AcceptSocket = null;
286             }
287 
288             if (!this.listenSocket.AcceptAsync(acceptEventArg))
289             {
290                 this.ProcessAccept(acceptEventArg);
291             }
292         }
293 
294         /// <summary>
295         /// 啟動服務,開始監聽
296         /// </summary>
297         /// <param name="port">Port where the server will listen for connection requests.</param>
298         internal void Start(Int32 port)
299         {
300             // 獲得主機相關信息
301             IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
302             IPEndPoint localEndPoint = new IPEndPoint(addressList[addressList.Length - 1], port);
303 
304             // 創建監聽socket
305             this.listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
306             this.listenSocket.ReceiveBufferSize = this.bufferSize;
307             this.listenSocket.SendBufferSize = this.bufferSize;
308 
309             if (localEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
310             {
311                 // 配置監聽socket為 dual-mode (IPv4 & IPv6) 
312                 // 27 is equivalent to IPV6_V6ONLY socket option in the winsock snippet below,
313                 this.listenSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
314                 this.listenSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, localEndPoint.Port));
315             }
316             else
317             {
318                 this.listenSocket.Bind(localEndPoint);
319             }
320 
321             // 開始監聽
322             this.listenSocket.Listen(this.numConnections);
323 
324             // 在監聽Socket上投遞一個接受請求。
325             this.StartAccept(null);
326 
327             // Blocks the current thread to receive incoming messages.
328             mutex.WaitOne();
329         }
330 
331         /// <summary>
332         /// 停止服務
333         /// </summary>
334         internal void Stop()
335         {
336             this.listenSocket.Close();
337             mutex.ReleaseMutex();
338         }
339 
340     }
341 }

 

 


免責聲明!

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



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