C# .NET Socket 简单实用框架

发表于:2017-9-15 10:25

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:寒空飞箭    来源:51Testing软件测试网采编

#
DotNet
#
dotnet
分享:
  背景:
  首先向各位前辈,大哥哥小姐姐问一声好~
  这是我第一次写博客,目前为一个即将步入大四的学生,上学期在一家公司实习了半年,后期发现没有动力,而且由于薪水问题(废话嘛),于是跳槽到这家新的公司。
  说到Socket,想必大家都或多或少有所涉及,从最初的计算机网络课程,讲述了tcp协议,而Socket就是对协议的进一步封装,使我们开发人员能够更加容易轻松的进行软件之间的通信。
  这个星期刚好接受一个共享车位锁的项目,需要使用Socket与硬件进行通信控制,说白了也就是给锁发送指令,控制其打开或者关闭,再就是对App开放操作接口,使其方便测试以及用户的使用。这其中核心就是Socket的使用,再开发出这个功能之后,我发现使用起来很不方便,于是耗时2天抽象其核心功能并封装成框架,最后使用这个框架将原来的项目重构并上线,极大的提高了软件的可拓展性,健壮性,容错率。
  个人坚信的原则:万物皆对象
  好了,不废话了,下面进入正文
  正文:
  1、首先简单讲下C#中Socket的简单使用。
  第一步:服务端监听某个端口
  第二步:客户端向服务端地址和端口发起Socket连接请求
  第三步:服务端收到连接请求后创建Socket连接,并维护这个连接队列。
  第四步:客户端和服务端已经建立双工通信(即双向通信),客户端和服务端可以轻松方便的给彼此发送信息。
  至于简单使用的具体实现代码全部被我封装到项目中了,如果需要学习简单的实现,可以看我的源码,也可以自行百度,有很多的教程
  2、核心,框架的使用。
  其实,说其为框架,可能有点牵强,因为每个人对框架都有自己的理解,但是类库和框架又有什么本质区别呢?全部都是代码~哈哈,扯远了
  首先,空说无凭,先放上所有的代码:
  服务端源文件:
  SocketServer.cs
   usingSystem;
  usingSystem.Collections.Generic;
  usingSystem.Net;
  usingSystem.Net.Sockets;
  namespaceColdairarrow.Util.Sockets
  {
  ///<summary>
  ///Socket服务端
  ///</summary>
  publicclassSocketServer
  {
  #region构造函数
  ///<summary>
  ///构造函数
  ///</summary>
  ///<paramname="ip">监听的IP地址</param>
  ///<paramname="port">监听的端口</param>
  publicSocketServer(stringip,intport)
  {
  _ip=ip;
  _port=port;
  }
  ///<summary>
  ///构造函数,监听IP地址默认为本机0.0.0.0
  ///</summary>
  ///<paramname="port">监听的端口</param>
  publicSocketServer(intport)
  {
  _ip="0.0.0.0";
  _port=port;
  }
  #endregion
  #region内部成员
  privateSocket_socket=null;
  privatestring_ip="";
  privateint_port=0;
  privatebool_isListen=true;
  privatevoidStartListen()
  {
  try
  {
  _socket.BeginAccept(asyncResult=>
  {
  try
  {
  SocketnewSocket=_socket.EndAccept(asyncResult);
  //马上进行下一轮监听,增加吞吐量
  if(_isListen)
  StartListen();
  SocketConnectionnewClient=newSocketConnection(newSocket,this)
  {
  HandleRecMsg=HandleRecMsg==null?null:newAction<byte[],SocketConnection,SocketServer>(HandleRecMsg),
  HandleClientClose=HandleClientClose==null?null:newAction<SocketConnection,SocketServer>(HandleClientClose),
  HandleSendMsg=HandleSendMsg==null?null:newAction<byte[],SocketConnection,SocketServer>(HandleSendMsg),
  HandleException=HandleException==null?null:newAction<Exception>(HandleException)
  };
  newClient.StartRecMsg();
  ClientList.AddLast(newClient);
  HandleNewClientConnected?.Invoke(this,newClient);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  },null);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  }
  #endregion
  #region外部接口
  ///<summary>
  ///开始服务,监听客户端
  ///</summary>
  publicvoidStartServer()
  {
  try
  {
  //实例化套接字(ip4寻址协议,流式传输,TCP协议)
  _socket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  //创建ip对象
  IPAddressaddress=IPAddress.Parse(_ip);
  //创建网络节点对象包含ip和port
  IPEndPointendpoint=newIPEndPoint(address,_port);
  //将监听套接字绑定到对应的IP和端口
  _socket.Bind(endpoint);
  //设置监听队列长度为Int32最大值(同时能够处理连接请求数量)
  _socket.Listen(int.MaxValue);
  //开始监听客户端
  StartListen();
  HandleServerStarted?.Invoke(this);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  }
  ///<summary>
  ///所有连接的客户端列表
  ///</summary>
  publicLinkedList<SocketConnection>ClientList{get;set;}=newLinkedList<SocketConnection>();
  ///<summary>
  ///关闭指定客户端连接
  ///</summary>
  ///<paramname="theClient">指定的客户端连接</param>
  publicvoidCloseClient(SocketConnectiontheClient)
  {
  theClient.Close();
  }
  #endregion
  #region公共事件
  ///<summary>
  ///异常处理程序
  ///</summary>
  publicAction<Exception>HandleException{get;set;}
  #endregion
  #region服务端事件
  ///<summary>
  ///服务启动后执行
  ///</summary>
  publicAction<SocketServer>HandleServerStarted{get;set;}
  ///<summary>
  ///当新客户端连接后执行
  ///</summary>
  publicAction<SocketServer,SocketConnection>HandleNewClientConnected{get;set;}
  ///<summary>
  ///服务端关闭客户端后执行
  ///</summary>
  publicAction<SocketServer,SocketConnection>HandleCloseClient{get;set;}
  #endregion
  #region客户端连接事件
  ///<summary>
  ///客户端连接接受新的消息后调用
  ///</summary>
  publicAction<byte[],SocketConnection,SocketServer>HandleRecMsg{get;set;}
  ///<summary>
  ///客户端连接发送消息后回调
  ///</summary>
  publicAction<byte[],SocketConnection,SocketServer>HandleSendMsg{get;set;}
  ///<summary>
  ///客户端连接关闭后回调
  ///</summary>
  publicAction<SocketConnection,SocketServer>HandleClientClose{get;set;}
  #endregion
  }
  }
  
  usingSystem;
  usingSystem.Net.Sockets;
  usingSystem.Text;
  namespaceColdairarrow.Util.Sockets
  {
  ///<summary>
  ///Socket连接,双向通信
  ///</summary>
  publicclassSocketConnection
  {
  #region构造函数
  publicSocketConnection(Socketsocket,SocketServerserver)
  {
  _socket=socket;
  _server=server;
  }
  #endregion
  #region私有成员
  privatereadonlySocket_socket;
  privatebool_isRec=true;
  privateSocketServer_server=null;
  privateboolIsSocketConnected()
  {
  boolpart1=_socket.Poll(1000,SelectMode.SelectRead);
  boolpart2=(_socket.Available==0);
  if(part1&&part2)
  returnfalse;
  else
  returntrue;
  }
  #endregion
  #region外部接口
  ///<summary>
  ///开始接受客户端消息
  ///</summary>
  publicvoidStartRecMsg()
  {
  try
  {
  byte[]container=newbyte[1024*1024*2];
  _socket.BeginReceive(container,0,container.Length,SocketFlags.None,asyncResult=>
  {
  try
  {
  intlength=_socket.EndReceive(asyncResult);
  //马上进行下一轮接受,增加吞吐量
  if(length>0&&_isRec&&IsSocketConnected())
  StartRecMsg();
  if(length>0)
  {
  byte[]recBytes=newbyte[length];
  Array.Copy(container,0,recBytes,0,length);
  //处理消息
  HandleRecMsg?.Invoke(recBytes,this,_server);
  }
  else
  Close();
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  Close();
  }
  },null);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  Close();
  }
  }
  ///<summary>
  ///发送数据
  ///</summary>
  ///<paramname="bytes">数据字节</param>
  publicvoidSend(byte[]bytes)
  {
  try
  {
  _socket.BeginSend(bytes,0,bytes.Length,SocketFlags.None,asyncResult=>
  {
  try
  {
  intlength=_socket.EndSend(asyncResult);
  HandleSendMsg?.Invoke(bytes,this,_server);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  },null);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  }
  ///<summary>
  ///发送字符串(默认使用UTF-8编码)
  ///</summary>
  ///<paramname="msgStr">字符串</param>
  publicvoidSend(stringmsgStr)
  {
  Send(Encoding.UTF8.GetBytes(msgStr));
  }
  ///<summary>
  ///发送字符串(使用自定义编码)
  ///</summary>
  ///<paramname="msgStr">字符串消息</param>
  ///<paramname="encoding">使用的编码</param>
  publicvoidSend(stringmsgStr,Encodingencoding)
  {
  Send(encoding.GetBytes(msgStr));
  }
  ///<summary>
  ///传入自定义属性
  ///</summary>
  publicobjectProperty{get;set;}
  ///<summary>
  ///关闭当前连接
  ///</summary>
  publicvoidClose()
  {
  try
  {
  _isRec=false;
  _socket.Disconnect(false);
  _server.ClientList.Remove(this);
  HandleClientClose?.Invoke(this,_server);
  _socket.Close();
  _socket.Dispose();
  GC.Collect();
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  }
  #endregion
  #region事件处理
  ///<summary>
  ///客户端连接接受新的消息后调用
  ///</summary>
  publicAction<byte[],SocketConnection,SocketServer>HandleRecMsg{get;set;}
  ///<summary>
  ///客户端连接发送消息后回调
  ///</summary>
  publicAction<byte[],SocketConnection,SocketServer>HandleSendMsg{get;set;}
  ///<summary>
  ///客户端连接关闭后回调
  ///</summary>
  publicAction<SocketConnection,SocketServer>HandleClientClose{get;set;}
  ///<summary>
  ///异常处理程序
  ///</summary>
  publicAction<Exception>HandleException{get;set;}
  #endregion
  }
  }
  复制代码
  复制代码
  usingSystem;
  usingSystem.Net;
  usingSystem.Net.Sockets;
  usingSystem.Text;
  namespaceColdairarrow.Util.Sockets
  {
  ///<summary>
  ///Socket客户端
  ///</summary>
  publicclassSocketClient
  {
  #region构造函数
  ///<summary>
  ///构造函数,连接服务器IP地址默认为本机127.0.0.1
  ///</summary>
  ///<paramname="port">监听的端口</param>
  publicSocketClient(intport)
  {
  _ip="127.0.0.1";
  _port=port;
  }
  ///<summary>
  ///构造函数
  ///</summary>
  ///<paramname="ip">监听的IP地址</param>
  ///<paramname="port">监听的端口</param>
  publicSocketClient(stringip,intport)
  {
  _ip=ip;
  _port=port;
  }
  #endregion
  #region内部成员
  privateSocket_socket=null;
  privatestring_ip="";
  privateint_port=0;
  privatebool_isRec=true;
  privateboolIsSocketConnected()
  {
  boolpart1=_socket.Poll(1000,SelectMode.SelectRead);
  boolpart2=(_socket.Available==0);
  if(part1&&part2)
  returnfalse;
  else
  returntrue;
  }
  ///<summary>
  ///开始接受客户端消息
  ///</summary>
  publicvoidStartRecMsg()
  {
  try
  {
  byte[]container=newbyte[1024*1024*2];
  _socket.BeginReceive(container,0,container.Length,SocketFlags.None,asyncResult=>
  {
  try
  {
  intlength=_socket.EndReceive(asyncResult);
  //马上进行下一轮接受,增加吞吐量
  if(length>0&&_isRec&&IsSocketConnected())
  StartRecMsg();
  if(length>0)
  {
  byte[]recBytes=newbyte[length];
  Array.Copy(container,0,recBytes,0,length);
  //处理消息
  HandleRecMsg?.Invoke(recBytes,this);
  }
  else
  Close();
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  Close();
  }
  },null);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  Close();
  }
  }
  #endregion
  #region外部接口
  ///<summary>
  ///开始服务,连接服务端
  ///</summary>
  publicvoidStartClient()
  {
  try
  {
  //实例化套接字(ip4寻址协议,流式传输,TCP协议)
  _socket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  //创建ip对象
  IPAddressaddress=IPAddress.Parse(_ip);
  //创建网络节点对象包含ip和port
  IPEndPointendpoint=newIPEndPoint(address,_port);
  //将监听套接字绑定到对应的IP和端口
  _socket.BeginConnect(endpoint,asyncResult=>
  {
  try
  {
  _socket.EndConnect(asyncResult);
  //开始接受服务器消息
  StartRecMsg();
  HandleClientStarted?.Invoke(this);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  },null);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  }
  ///<summary>
  ///发送数据
  ///</summary>
  ///<paramname="bytes">数据字节</param>
  publicvoidSend(byte[]bytes)
  {
  try
  {
  _socket.BeginSend(bytes,0,bytes.Length,SocketFlags.None,asyncResult=>
  {
  try
  {
  intlength=_socket.EndSend(asyncResult);
  HandleSendMsg?.Invoke(bytes,this);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  },null);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  }
  ///<summary>
  ///发送字符串(默认使用UTF-8编码)
  ///</summary>
  ///<paramname="msgStr">字符串</param>
  publicvoidSend(stringmsgStr)
  {
  Send(Encoding.UTF8.GetBytes(msgStr));
  }
  ///<summary>
  ///发送字符串(使用自定义编码)
  ///</summary>
  ///<paramname="msgStr">字符串消息</param>
  ///<paramname="encoding">使用的编码</param>
  publicvoidSend(stringmsgStr,Encodingencoding)
  {
  Send(encoding.GetBytes(msgStr));
  }
  ///<summary>
  ///传入自定义属性
  ///</summary>
  publicobjectProperty{get;set;}
  ///<summary>
  ///关闭与服务器的连接
  ///</summary>
  publicvoidClose()
  {
  try
  {
  _isRec=false;
  _socket.Disconnect(false);
  HandleClientClose?.Invoke(this);
  }
  catch(Exceptionex)
  {
  HandleException?.Invoke(ex);
  }
  }
  #endregion
  #region事件处理
  ///<summary>
  ///客户端连接建立后回调
  ///</summary>
  publicAction<SocketClient>HandleClientStarted{get;set;}
  ///<summary>
  ///处理接受消息的委托
  ///</summary>
  publicAction<byte[],SocketClient>HandleRecMsg{get;set;}
  ///<summary>
  ///客户端连接发送消息后回调
  ///</summary>
  publicAction<byte[],SocketClient>HandleSendMsg{get;set;}
  ///<summary>
  ///客户端连接关闭后回调
  ///</summary>
  publicAction<SocketClient>HandleClientClose{get;set;}
  ///<summary>
  ///异常处理程序
  ///</summary>
  publicAction<Exception>HandleException{get;set;}
  #endregion
  }
  }
  上面放上的是框架代码,接下来介绍下如何使用
  首先,服务端使用方式:
  usingColdairarrow.Util.Sockets;
  usingSystem;
  usingSystem.Text;
  namespaceConsole_Server
  {
  classProgram
  {
  staticvoidMain(string[]args)
  {
  //创建服务器对象,默认监听本机0.0.0.0,端口12345
  SocketServerserver=newSocketServer(12345);
  //处理从客户端收到的消息
  server.HandleRecMsg=newAction<byte[],SocketConnection,SocketServer>((bytes,client,theServer)=>
  {
  stringmsg=Encoding.UTF8.GetString(bytes);
  Console.WriteLine($"收到消息:{msg}");
  });
  //处理服务器启动后事件
  server.HandleServerStarted=newAction<SocketServer>(theServer=>
  {
  Console.WriteLine("服务已启动************");
  });
  //处理新的客户端连接后的事件
  server.HandleNewClientConnected=newAction<SocketServer,SocketConnection>((theServer,theCon)=>
  {
  Console.WriteLine($@"一个新的客户端接入,当前连接数:{theServer.ClientList.Count}");
  });
  //处理客户端连接关闭后的事件
  server.HandleClientClose=newAction<SocketConnection,SocketServer>((theCon,theServer)=>
  {
  Console.WriteLine($@"一个客户端关闭,当前连接数为:{theServer.ClientList.Count}");
  });
  //处理异常
  server.HandleException=newAction<Exception>(ex=>
  {
  Console.WriteLine(ex.Message);
  });
  //服务器启动
  server.StartServer();
  while(true)
  {
  Console.WriteLine("输入:quit,关闭服务器");
  stringop=Console.ReadLine();
  if(op=="quit")
  break;
  }
  }
  }
  }
  客户端使用方式:
  usingColdairarrow.Util.Sockets;
  usingSystem;
  usingSystem.Text;
  namespaceConsole_Client
  {
  classProgram
  {
  staticvoidMain(string[]args)
  {
  //创建客户端对象,默认连接本机127.0.0.1,端口为12345
  SocketClientclient=newSocketClient(12345);
  //绑定当收到服务器发送的消息后的处理事件
  client.HandleRecMsg=newAction<byte[],SocketClient>((bytes,theClient)=>
  {
  stringmsg=Encoding.UTF8.GetString(bytes);
  Console.WriteLine($"收到消息:{msg}");
  });
  //绑定向服务器发送消息后的处理事件
  client.HandleSendMsg=newAction<byte[],SocketClient>((bytes,theClient)=>
  {
  stringmsg=Encoding.UTF8.GetString(bytes);
  Console.WriteLine($"向服务器发送消息:{msg}");
  });
  //开始运行客户端
  client.StartClient();
  while(true)
  {
  Console.WriteLine("输入:quit关闭客户端,输入其它消息发送到服务器");
  stringstr=Console.ReadLine();
  if(str=="quit")
  {
  client.Close();
  break;
  }
  else
  {
  client.Send(str);
  }
  }
  }
  }
  }
  最后运行测试截图:
  总结:
  其最方便之处在于,将如何创建连接封装掉,使用人员只需关注连接后发送什么数据,接收到数据后应该如何处理,等等其它的很多事件的处理,这其中主要依托于匿名委托的使用,Lambda表达式的使用。
  框架里面主要使用了异步通讯,以及如何控制连接,详细我就不多说了,大家应该一看就懂,我只希望能给大家带来便利,最后大家有任何问题、意见、想法,都可以给我留言。
  最后,附上所有源码项目地址,若觉得有一定价值,还请点赞~
  GitHub地址:https://github.com/Coldairarrow/Sockets
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号