直接Ctrl+c再Ctrl+v就能直接用了,纯小白教程。
类库+调用方法
- 类库
class CsSocketService
{
/// <summary>
/// 作者:WangJunLiang || Wechat:Joronwongx
/// </summary>
public delegate void ReceClientData(string strRp, byte[] Buf, int nBufLenght);
public event ReceClientData SendReceEnvent;
public struct SocketServiceIP
{
public string strIpAddress;
public int nPort;
public int nMaxClientConnectCnt;
};
#region 线程管理
//管理者线程
private Socket m_ServiceMaster = null;
private BackgroundWorker m_ClientAdministrator_BackgroundWorker = null;
//用户线程
public struct SocketServiceChild
{
public Socket socket;
public BackgroundWorker backgroundWorker;
};
public Dictionary<string, SocketServiceChild> m_LSocketServiceChild = new Dictionary<string, SocketServiceChild>(); //是二叉树式的存储结构,不支持用索引来取值,想取只能遍历
#endregion
#region 监听服务
//创建多个子服务器的消息接收线程
private void CreateClientReceClick(object sender, DoWorkEventArgs e)
{
while (!m_ClientAdministrator_BackgroundWorker.CancellationPending)
{
Socket socketItem = m_ServiceMaster.Accept(); //阻塞监听
if (m_ClientAdministrator_BackgroundWorker.CancellationPending) //支线程是否被挂起取消
break;
if (socketItem != null)
{
BackgroundWorker ServiceChild_BackgroundWorker = new BackgroundWorker();
ServiceChild_BackgroundWorker.DoWork += ReceClientDataClick; //持续监听绑定的客户端
ServiceChild_BackgroundWorker.WorkerSupportsCancellation