NET平臺下TCP實現IOCP例子
MainForm.cs窗體程式碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace IocpServer
{
public partial class MainForm : Form
{
public delegate void SetListBoxCallBack(string str);
public SetListBoxCallBack setlistboxcallback;
public void SetListBox(string str)
{
infoList.Items.Insert(0, str);
infoList.SelectedIndex = 0;
}
private IoServer iocp = new IoServer(2, 1024);
public MainForm()
{
InitializeComponent();
#region 初始化IP 和埠號
IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
ipStr.Text = addressList[addressList.Length - 1].ToString();
portStr.Text = "1086";
#endregion
setlistboxcallback = new SetListBoxCallBack(SetListBox);
}
private void startBtn_Click(object sender, EventArgs e)
{
iocp.Start(1086);
iocp.mainForm = this;
startBtn.Enabled = false;
stopBtn.Enabled = true;
SetListBox("監聽開啟...");
}
private void stopBtn_Click(object sender, EventArgs e)
{
iocp.Stop();
startBtn.Enabled = true;
stopBtn.Enabled = false;
SetListBox("監聽停止...");
}
private void exitBtn_Click(object sender, EventArgs e)
{
if (stopBtn.Enabled)
iocp.Stop();
this.Close();
}
private void clearBtn_Click(object sender, EventArgs e)
{
infoList.Items.Clear();
}
}
}
IoServer.cs
基於SocketAsyncEventArgs
實現 IOCP
伺服器
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace IocpServer
{
/// <summary>
/// 基於SocketAsyncEventArgs 實現 IOCP 伺服器
/// </summary>
internal sealed class IoServer
{
/// <summary>
/// 監聽Socket,用於接受客戶端的連線請求
/// </summary>
private Socket listenSocket;
/// <summary>
/// 用於伺服器執行的互斥同步物件
/// </summary>
private static Mutex mutex = new Mutex();
/// <summary>
/// 用於每個I/O Socket操作的緩衝區大小
/// </summary>
private Int32 bufferSize;
/// <summary>
/// 伺服器上連線的客戶端總數
/// </summary>
private Int32 numConnectedSockets;
/// <summary>
/// 伺服器能接受的最大連線數量
/// </summary>
private Int32 numConnections;
/// <summary>
/// 完成埠上進行投遞所用的IoContext物件池
/// </summary>
private IoContextPool ioContextPool;
public MainForm mainForm;
/// <summary>
/// 建構函式,建立一個未初始化的伺服器例項
/// </summary>
/// <param name="numConnections">伺服器的最大連線資料</param>
/// <param name="bufferSize"></param>
internal IoServer(Int32 numConnections, Int32 bufferSize)
{
this.numConnectedSockets = 0;
this.numConnections = numConnections;
this.bufferSize = bufferSize;
this.ioContextPool = new IoContextPool(numConnections);
// 為IoContextPool預分配SocketAsyncEventArgs物件
for (Int32 i = 0; i < this.numConnections; i++)
{
SocketAsyncEventArgs ioContext = new SocketAsyncEventArgs();
ioContext.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted);
ioContext.SetBuffer(new Byte[this.bufferSize], 0, this.bufferSize);
// 將預分配的物件加入SocketAsyncEventArgs物件池中
this.ioContextPool.Add(ioContext);
}
}
/// <summary>
/// 當Socket上的傳送或接收請求被完成時,呼叫此函式
/// </summary>
/// <param name="sender">激發事件的物件</param>
/// <param name="e">與傳送或接收完成操作相關聯的SocketAsyncEventArg物件</param>
private void OnIOCompleted(object sender, SocketAsyncEventArgs e)
{
// Determine which type of operation just completed and call the associated handler.
switch (e.LastOperation)
{
case SocketAsyncOperation.Receive:
this.ProcessReceive(e);
break;
case SocketAsyncOperation.Send:
this.ProcessSend(e);
break;
default:
throw new ArgumentException("The last operation completed on the socket was not a receive or send");
}
}
/// <summary>
///接收完成時處理函式
/// </summary>
/// <param name="e">與接收完成操作相關聯的SocketAsyncEventArg物件</param>
private void ProcessReceive(SocketAsyncEventArgs e)
{
// 檢查遠端主機是否關閉連線
if (e.BytesTransferred > 0)
{
if (e.SocketError == SocketError.Success)
{
Socket s = (Socket)e.UserToken;
//判斷所有需接收的資料是否已經完成
if (s.Available == 0)
{
//獲取接收到的資料
byte[] ByteArray = new byte[e.BytesTransferred];
Array.Copy(e.Buffer, 0, ByteArray, 0, ByteArray.Length);
//設定傳送資料(自定義資料)
//byte[] bt = new byte[10] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
//e.SetBuffer(e.Offset, bt.Length);
//Array.Copy(bt, 0, e.Buffer, 0, bt.Length);
//e.SetBuffer(e.Offset, bt.Length);
//設定傳送的資料(原樣返回)
Array.Copy(e.Buffer, 0, e.Buffer, e.BytesTransferred, e.BytesTransferred);
e.SetBuffer(e.Offset, e.BytesTransferred);
if (!s.SendAsync(e)) //投遞傳送請求,這個函式有可能同步傳送出去,這時返回false,並且不會引發SocketAsyncEventArgs.Completed事件
{
// 同步傳送時處理髮送完成事件
this.ProcessSend(e);
}
}
else if (!s.ReceiveAsync(e)) //為接收下一段資料,投遞接收請求,這個函式有可能同步完成,這時返回false,並且不會引發SocketAsyncEventArgs.Completed事件
{
// 同步接收時處理接收完成事件
this.ProcessReceive(e);
}
}
else
{
this.ProcessError(e);
}
}
else
{
this.CloseClientSocket(e);
}
}
/// <summary>
/// 傳送完成時處理函式
/// </summary>
/// <param name="e">與傳送完成操作相關聯的SocketAsyncEventArg物件</param>
private void ProcessSend(SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
Socket s = (Socket)e.UserToken;
//接收時根據接收的位元組數收縮了緩衝區的大小,因此投遞接收請求時,恢復緩衝區大小
e.SetBuffer(0, bufferSize);
if (!s.ReceiveAsync(e)) //投遞接收請求
{
// 同步接收時處理接收完成事件
this.ProcessReceive(e);
}
}
else
{
this.ProcessError(e);
}
}
/// <summary>
/// 處理socket錯誤
/// </summary>
/// <param name="e"></param>
private void ProcessError(SocketAsyncEventArgs e)
{
Socket s = e.UserToken as Socket;
IPEndPoint localEp = s.LocalEndPoint as IPEndPoint;
this.CloseClientSocket(s, e);
string outStr = String.Format("套接字錯誤 {0}, IP {1}, 操作 {2}。", (Int32)e.SocketError, localEp, e.LastOperation);
mainForm.Invoke(mainForm.setlistboxcallback, outStr);
//Console.WriteLine("Socket error {0} on endpoint {1} during {2}.", (Int32)e.SocketError, localEp, e.LastOperation);
}
/// <summary>
/// 關閉socket連線
/// </summary>
/// <param name="e">SocketAsyncEventArg associated with the completed send/receive operation.</param>
private void CloseClientSocket(SocketAsyncEventArgs e)
{
Socket s = e.UserToken as Socket;
this.CloseClientSocket(s, e);
}
private void CloseClientSocket(Socket s, SocketAsyncEventArgs e)
{
Interlocked.Decrement(ref this.numConnectedSockets);
// SocketAsyncEventArg 物件被釋放,壓入可重用佇列。
this.ioContextPool.Push(e);
string outStr = String.Format("客戶 {0} 斷開, 共有 {1} 個連線。", s.RemoteEndPoint.ToString(), this.numConnectedSockets);
mainForm.Invoke(mainForm.setlistboxcallback, outStr);
//Console.WriteLine("A client has been disconnected from the server. There are {0} clients connected to the server", this.numConnectedSockets);
try
{
s.Shutdown(SocketShutdown.Send);
}
catch (Exception)
{
// Throw if client has closed, so it is not necessary to catch.
}
finally
{
s.Close();
}
}
/// <summary>
/// accept 操作完成時回撥函式
/// </summary>
/// <param name="sender">Object who raised the event.</param>
/// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
private void OnAcceptCompleted(object sender, SocketAsyncEventArgs e)
{
this.ProcessAccept(e);
}
/// <summary>
/// 監聽Socket接受處理
/// </summary>
/// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
private void ProcessAccept(SocketAsyncEventArgs e)
{
Socket s = e.AcceptSocket;
if (s.Connected)
{
try
{
SocketAsyncEventArgs ioContext = this.ioContextPool.Pop();
if (ioContext != null)
{
// 從接受的客戶端連線中取資料配置ioContext
ioContext.UserToken = s;
Interlocked.Increment(ref this.numConnectedSockets);
string outStr = String.Format("客戶 {0} 連入, 共有 {1} 個連線。", s.RemoteEndPoint.ToString(),this.numConnectedSockets);
mainForm.Invoke(mainForm.setlistboxcallback,outStr);
//Console.WriteLine("Client connection accepted. There are {0} clients connected to the server",
//this.numConnectedSockets);
if (!s.ReceiveAsync(ioContext))
{
this.ProcessReceive(ioContext);
}
}
else //已經達到最大客戶連線數量,在這接受連線,傳送“連線已經達到最大數”,然後斷開連線
{
s.Send(Encoding.Default.GetBytes("連線已經達到最大數!"));
string outStr = String.Format("連線已滿,拒絕 {0} 的連線。", s.RemoteEndPoint);
mainForm.Invoke(mainForm.setlistboxcallback, outStr);
s.Close();
}
}
catch (SocketException ex)
{
Socket token = e.UserToken as Socket;
string outStr = String.Format("接收客戶 {0} 資料出錯, 異常資訊: {1} 。", token.RemoteEndPoint, ex.ToString());
mainForm.Invoke(mainForm.setlistboxcallback, outStr);
//Console.WriteLine("Error when processing data received from {0}:\r\n{1}", token.RemoteEndPoint, ex.ToString());
}
catch (Exception ex)
{
mainForm.Invoke(mainForm.setlistboxcallback, "異常:" + ex.ToString());
}
// 投遞下一個接受請求
this.StartAccept(e);
}
}
/// <summary>
/// 從客戶端開始接受一個連線操作
/// </summary>
/// <param name="acceptEventArg">The context object to use when issuing
/// the accept operation on the server's listening socket.</param>
private void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted);
}
else
{
// 重用前進行物件清理
acceptEventArg.AcceptSocket = null;
}
if (!this.listenSocket.AcceptAsync(acceptEventArg))
{
this.ProcessAccept(acceptEventArg);
}
}
/// <summary>
/// 啟動服務,開始監聽
/// </summary>
/// <param name="port">Port where the server will listen for connection requests.</param>
internal void Start(Int32 port)
{
// 獲得主機相關資訊
IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
IPEndPoint localEndPoint = new IPEndPoint(addressList[addressList.Length - 1], port);
// 建立監聽socket
this.listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
this.listenSocket.ReceiveBufferSize = this.bufferSize;
this.listenSocket.SendBufferSize = this.bufferSize;
if (localEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
{
// 配置監聽socket為 dual-mode (IPv4 & IPv6)
// 27 is equivalent to IPV6_V6ONLY socket option in the winsock snippet below,
this.listenSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
this.listenSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, localEndPoint.Port));
}
else
{
this.listenSocket.Bind(localEndPoint);
}
// 開始監聽
this.listenSocket.Listen(this.numConnections);
// 在監聽Socket上投遞一個接受請求。
this.StartAccept(null);
// Blocks the current thread to receive incoming messages.
mutex.WaitOne();
}
/// <summary>
/// 停止服務
/// </summary>
internal void Stop()
{
this.listenSocket.Close();
mutex.ReleaseMutex();
}
}
}
IoContextPool.cs
完成埠上進行投遞所用的IoContext
物件池
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
namespace IocpServer
{
/// <summary>
/// 與每個客戶Socket相關聯,進行Send和Receive投遞時所需要的引數
/// </summary>
internal sealed class IoContextPool
{
List<SocketAsyncEventArgs> pool; //為每一個Socket客戶端分配一個SocketAsyncEventArgs,用一個List管理,在程式啟動時建立。
Int32 capacity; //pool物件池的容量
Int32 boundary; //已分配和未分配物件的邊界,大的是已經分配的,小的是未分配的
internal IoContextPool(Int32 capacity)
{
this.pool = new List<SocketAsyncEventArgs>(capacity);
this.boundary = 0;
this.capacity = capacity;
}
/// <summary>
/// 往pool物件池中增加新建立的物件,因為這個程式在啟動時會建立好所有物件,
/// 故這個方法只在初始化時會被呼叫,因此,沒有加鎖。
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
internal bool Add(SocketAsyncEventArgs arg)
{
if (arg != null && pool.Count < capacity)
{
pool.Add(arg);
boundary++;
return true;
}
else
return false;
}
/// <summary>
/// 取出集合中指定物件,內部使用
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
//internal SocketAsyncEventArgs Get(int index)
//{
// if (index >= 0 && index < capacity)
// return pool[index];
// else
// return null;
//}
/// <summary>
/// 從物件池中取出一個物件,交給一個socket來進行投遞請求操作
/// </summary>
/// <returns></returns>
internal SocketAsyncEventArgs Pop()
{
lock (this.pool)
{
if (boundary > 0)
{
--boundary;
return pool[boundary];
}
else
return null;
}
}
/// <summary>
/// 一個socket客戶斷開,與其相關的IoContext被釋放,重新投入Pool中,備用。
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
internal bool Push(SocketAsyncEventArgs arg)
{
if (arg != null)
{
lock (this.pool)
{
int index = this.pool.IndexOf(arg, boundary); //找出被斷開的客戶,此處一定能查到,因此index不可能為-1,必定要大於0。
if (index == boundary) //正好是邊界元素
boundary++;
else
{
this.pool[index] = this.pool[boundary]; //將斷開客戶移到邊界上,邊界右移
this.pool[boundary++] = arg;
}
}
return true;
}
else
return false;
}
}
}
執行結果如圖:
相關文章
- .NET平臺系列10 .NET統一平臺願景
- .NET平臺系列13 .NET5 統一平臺
- [Hei.Captcha] Asp.Net Core 跨平臺驗證碼實現APTASP.NET
- GRPC 多平臺實現RPC
- 實現在安卓平臺下的即時通訊安卓
- .NET Core 跨平臺
- .net ocre 程式崩潰自動dump在多平臺中的實現
- 基於.NET 5實現的開源通用許可權管理平臺
- 【Nginx】Windows平臺下配置Nginx服務實現負載均衡NginxWindows負載
- .NET平臺系列5 .NET Core 簡介
- 實體平臺可以親臨現場實體的靠譜平臺18388858011
- Python使用socket_TCP實現小檔案下載PythonTCP
- 實現Avalonia平臺下低配版的Dock控制元件:實現TabControl的可關閉控制元件
- .Net平臺的GC垃圾回收GC
- .NET跨平臺實踐:.NetCore、.Net5/6 Linux守護程式設計NetCoreLinux程式設計
- .NET平臺系列9 .NET Core 3.0 / .NET Core 3.1 詳解
- 在 iOS 平臺實現Ping 和 tracerouteiOS
- 打造跨平臺.NET Core後臺服務
- Django實現教育平臺全程記錄-----後臺管理Django
- .NET 平臺系列6 .NET Core 發展歷程
- .NET平臺系列8 .NET Core 各版本新功能
- .NET6 平臺系列4 .NET開源之路
- .NET6 平臺系列3 .NET CLR 詳解
- .net core下訪問控制層的實現
- ASP.NET MVC 反射例子ASP.NETMVC反射
- .NET平臺系列22:.NET Core/.NET5/.NET6 對比 .NET FrameworkFramework
- .NET平臺系列30:.NET Core/.NET 學習資源彙總
- Advanced .Net Debugging 9:平臺互用性
- 【.NET 遇上 GraphQL】 ChilliCream 平臺介紹
- .NET探索平臺條件編譯編譯
- .Net Core與跨平臺時區
- 億級流量實驗平臺設計與實現
- 計算機網路再次整理————tcp例子[五]計算機網路TCP
- .NET TCP、UDP、Socket、WebSocketTCPUDPWeb
- IoT平臺如何實現業務配置中心
- [轉]:多程式等待的跨平臺實現
- springboot+Vue 實現介面測試平臺Spring BootVue
- 如何實現視訊加密全平臺播放加密