C#完成异步套接字封装server与client处理方案 发表时间:2023-07-28 来源:明辉站整理相关软件相关文章人气: [摘要]C#实现异步套接字封装server与client解决方案 之前一直用C#些了很多管理软件,包括c/s , b/s ,之前一直都是同步写法,相信大家都用ajax异步请求数据,那能不能实... C#实现异步套接字封装server与client解决方案
之前一直用C#些了很多管理软件,包括c/s , b/s ,之前一直都是同步写法,相信大家都用ajax异步请求数据,那能不能实现 C#实现异步套接字封装server与client 呢,答案是肯定的。
今天文章中写的是异步,纯粹的异步,当然很多人看来很简单了,而且里面很多东西值得商榷,不过说真的,我真心感谢C#的线程池,不然我还要自己去写个threadpool。而且我没办法保证我写的没问题。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace PPT.Comm
{
///
/// 接收数据流
///
/// 异步套接字
/// 接收到的数据流
public delegate void AsyncDataAcceptedEventHandler(AsyncSocket m_pSocket, byte[] m_pDatagram);
///
/// 发送完毕
///
/// 异步套接字
/// 发送结果
public delegate void AsyncDataSendedEventHandler(AsyncSocket m_pSocket, bool m_pIsSuccess);
///
/// 接收连接委托
///
/// 异步套接字
public delegate void AsyncSocketAcceptEventHandler(AsyncSocket m_pSocket);
///
/// 关闭连接委托
///
/// 异步套接字
public delegate void AsyncSocketClosedEventHandler(AsyncSocket m_pSocket);
///
/// State object for receiving data from remote device.
///
class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024 * 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
///
/// 异步SOCKET
///
public class AsyncSocket
{
#region 私有字段 成员
private Socket m_socket = null; //socket
string m_id = ""; //socket唯一标识,GUID
private readonly bool m_isSerevr; //服务器标志位
private int m_iBackBag;
private string m_ipAddress;
private int m_port;
private AsyncDataAcceptedEventHandler m_onAsyncDataAcceptedEvent = null; //接收数据流
private AsyncDataSendedEventHandler m_onAsyncDataSendedEvent = null; //发送结束
private AsyncSocketAcceptEventHandler m_onAsyncSocketAcceptEvent = null; //接收连接
private AsyncSocketClosedEventHandler m_onAsyncSocketClosedEvent = null; //关闭连接
#endregion
#region 公共属性 成员
///
/// 获取SOCKET标志位
///
public string ID
{
get
{
return m_id;
}
}
///
/// 设置或获取机器标志位
///
public string MachineKey
{
set;
get;
}
///
/// 获取、设置连接对象
///
public Socket LinkObject
{
get
{
return m_socket;
}
set
{
m_socket = value;
}
}
///
/// 设置或获取线程退出标识
///
public bool IsExit { set; get; }
#endregion
#region 公共事件 成员
///
/// 连接关闭事件
///
public event AsyncSocketClosedEventHandler AsyncSocketClosedEvent
{
add
{
m_onAsyncSocketClosedEvent += value;
}
remove
{
m_onAsyncSocketClosedEvent -= value;
}
}
///
/// 连接接收事件
///
public event AsyncSocketAcceptEventHandler AsyncSocketAcceptEvent
{
add
{
m_onAsyncSocketAcceptEvent += value;
}
remove
{
m_onAsyncSocketAcceptEvent -= value;
}
}
///
/// 数据接收完成事件
///
public event AsyncDataAcceptedEventHandler AsyncDataAcceptedEvent
{
add
{
this.m_onAsyncDataAcceptedEvent += value;
}
remove
{
this.m_onAsyncDataAcceptedEvent -= value;
}
}
///
/// 数据发送完成事件
///
public event AsyncDataSendedEventHandler AsyncDataSendedEvent
{
add
{
m_onAsyncDataSendedEvent += value;
}
remove
{
m_onAsyncDataSendedEvent -= value;
}
}
#endregion
#region 构造函数 成员
///
/// 构造函数
///
/// 主机地址,可为机器名或者IP
/// 主机端口
/// 是否作为服务器,默认为false
/// 支持多少个客户端
public AsyncSocket(string m_pHostAddrss, int m_pHostPort, bool m_pIsAsServer = false, int m_pIBackBag = 10)
{
m_isSerevr = m_pIsAsServer;
m_iBackBag = m_pIBackBag;
m_ipAddress = m_pHostAddrss;
m_port = m_pHostPort;
m_id = Guid.NewGuid().ToString();
}
///
/// 构造函数,用于服务器构造与客户端的异步socket
///
/// 客户端socket
private AsyncSocket(Socket linkObject)
{
m_socket = linkObject;
m_id = Guid.NewGuid().ToString();
}
#endregion
#region 公共方法
///
/// 打开通道
///
public void AsyncOpen()
{
if (m_isSerevr)
{
IPAddress ip = Dns.GetHostAddresses(m_ipAddress)[0];
IPEndPoint ipe = new IPEndPoint(ip, m_port);
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_socket.Bind(ipe);
m_socket.Listen(m_iBackBag);
m_socket.BeginAccept(new AsyncCallback(AcceptCallBack), null);//异步
}
else
{
IPAddress ip = Dns.GetHostAddresses(m_ipAddress)[0];
IPEndPoint ipe = new IPEndPoint(ip, m_port);
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_socket.Connect(ipe);
}
}
///
/// 发送二进制数据
///
///
public void AsyncSend(byte[] SendData)
{
m_socket.BeginSend(SendData, 0, SendData.Length, 0, new AsyncCallback(SendCallBack), m_socket);
}
///
/// 关闭通道
///
public void AsyncClose()
{
if (!m_isSerevr)
{
m_socket.Shutdown(SocketShutdown.Both);//关闭接收发送流
m_socket.BeginDisconnect(false, CloseCallBack, m_socket);//开始尝试断开
}
else
{
m_socket.Shutdown(SocketShutdown.Both);//关闭接收发送流
Thread.Sleep(200);//等待现有任务处理完成
m_socket.Dispose();//释放所有本地资源
}
}
///
/// 开始接受数据,连接建立之后,调用此方法
///
public void BeginAcceptData()
{
//开始接收数据
StateObject state = new StateObject();
state.workSocket = m_socket;
m_socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
#endregion
#region 私有方法 成员
#endregion
#region 回调函数 成员
///
/// 接受客户端连接处理
///
///
private void AcceptCallBack(IAsyncResult ar)
{
Socket handler = m_socket.EndAccept(ar);
AsyncSocket NewSocket = new AsyncSocket(handler);
//激发事件,异步触发
if (m_onAsyncSocketAcceptEvent != null)
foreach (AsyncSocketAcceptEventHandler item in m_onAsyncSocketAcceptEvent.GetInvocationList())
item.BeginInvoke(NewSocket, null, null);
//继续投递监听请求
m_socket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
}
///
/// 接受字节流处理
///
///
private void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = ar.AsyncState as StateObject;
//读取数据
int bytesRead = m_socket.EndReceive(ar);
if (bytesRead > 0)
{
byte[] _Readbyte = new byte[bytesRead];
Array.Copy(state.buffer, 0, _Readbyte, 0, bytesRead);
//接收完成,激发事件
if (m_onAsyncDataAcceptedEvent != null)
foreach (AsyncDataAcceptedEventHandler item in m_onAsyncDataAcceptedEvent.GetInvocationList())
item.BeginInvoke(this, _Readbyte, null, null);
state = new StateObject();//继续投递接收委托
state.workSocket = m_socket;
m_socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
}
catch (SocketException)
{
if (m_onAsyncSocketClosedEvent != null)
foreach (AsyncSocketClosedEventHandler item in m_onAsyncSocketClosedEvent.GetInvocationList())
item.BeginInvoke(this, null, null);
}
}
///
/// 发送结束处理
///
///
private void SendCallBack(IAsyncResult ar)
{
try
{
m_socket.EndSend(ar);
if (m_onAsyncDataSendedEvent != null)
foreach (AsyncDataSendedEventHandler item in m_onAsyncDataSendedEvent.GetInvocationList())
item.BeginInvoke(this, true, null, null);
}
catch (SocketException)
{
if (m_onAsyncDataSendedEvent != null)
foreach (AsyncDataSendedEventHandler item in m_onAsyncDataSendedEvent.GetInvocationList())
item.BeginInvoke(this, false, null, null);
if (m_onAsyncSocketClosedEvent != null)
foreach (AsyncSocketClosedEventHandler item in m_onAsyncSocketClosedEvent.GetInvocationList())
item.BeginInvoke(this, null, null);
}
}
///
/// 关闭后处理
///
///
private void CloseCallBack(IAsyncResult ar)
{
try
{
m_socket.EndDisconnect(ar);
m_socket.Dispose();
if (m_onAsyncDataSendedEvent != null)
foreach (AsyncSocketClosedEventHandler item in m_onAsyncSocketClosedEvent.GetInvocationList())
item.BeginInvoke(this, null, null);
}
catch (SocketException)
{
if (m_onAsyncSocketClosedEvent != null)
foreach (AsyncSocketClosedEventHandler item in m_onAsyncSocketClosedEvent.GetInvocationList())
item.BeginInvoke(this, null, null);
}
}
#endregion
}
}
主要的代码全部放出,注释也写的很详细,当然不能保证我写的代码没有问题,但是本人测试过,应该没有打的问题。 学习教程快速掌握从入门到精通的电脑知识 | |