运维开发网

你知道C的基于socket的网络通信类吗

运维开发网 https://www.qedev.com 2022-04-14 15:55 出处:网络
这篇文章主要为大家详细介绍了C#基于Socket的网络通信类,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

这篇文章主要为大家详细介绍了C#基于Socket的网络通信类,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助


摘要

之所以封装socket通信库,是因为直接使用Socket进行网络通信编程相对复杂,尤其是新手。实际上,微软从年起就为TCP和UDP通信提供了高级封装类。net 2.0如下:

TcpListenerTcpClientUdpClient

微软从年起就提供了基于任务的异步通信接口。net 4.0。但是直接使用socket包库,socket本身的很多细节是自己控制不了的。本文的目的是提供一个套接字包供参考。本文在展示部分封装了TCP通信库,UDP封装也可以打个比方:

CusTcpListenerCusTcpClient


代码using System;using System.Text;using System.Net.Sockets;using System.Net; namespace NetDemo{ // 网络操作相关的类 public class InternetProHelper { // 检查设置的端口号是否正确,并返回正确的端口号,无效端口号返回-1 public static int GetNetPort(string NetPort) { //声明返回的正确端口号 int resPort = -1; //检测端口号 try { //传入的端口号为空则抛出异常 if (NetPort == "") { throw new Exception("端口号不能为空!"); } //检测端口范围 if ((Convert.ToInt32(NetPort) lt; ushort.MinValue) || (Convert.ToInt32(NetPort) gt; ushort.MaxValue)) { throw new Exception("端口号范围无效!"); } //为端口号赋值 resPort = Convert.ToInt32(NetPort); } catch (Exception ex) { string errMessage = ex.Message; } return resPort; } public static IPAddress StringToIPAddress(string NetIP) { // 将字符串形式的IP地址转换成IPAddress对象 return IPAddress.Parse(NetIP); } public static string LocalHostName { // 获取本机的计算机名 get { return Dns.GetHostName(); } } public static string LANIP { // 获取本机的局域网IP get { //获取本机的IP列表,IP列表中的第一项是局域网IP,第二项是广域网IP IPAddress[] IPaddrList = Dns.GetHostEntry(Dns.GetHostName()).AddressList; //如果本机IP列表为空,则返回空字符串 if (IPaddrList.Length lt; 1) { return ""; } //返回本机的局域网IP return IPaddrList[0].ToString(); } } public static string GetClientIP(Socket clientSocket) { // 获取远程客户机的IP地址 IPEndPoint client = (IPEndPoint)clientSocket.RemoteEndPoint;//客户端的NetSocket对象 return client.Address.ToString(); } public static IPEndPoint CreateIPEndPoint(string NetIP, int NetPort) { // 创建一个IPEndPoint对象 IPAddress ipAddress = StringToIPAddress(NetIP); return new IPEndPoint(ipAddress, NetPort); } public static TcpListener CreateTcpListener() { //创建一个自动分配的网络节点 IPAddress ipAddress = IPAddress.Any; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 0); return new TcpListener(localEndPoint); } public static TcpListener CreateTcpListener(string NetIP, int NetPort) { //创建一个网络节点 IPAddress ipAddress = StringToIPAddress(NetIP); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, NetPort); return new TcpListener(localEndPoint); } public static Socket CreateTcpSocket() { // 创建一个基于TCP协议的Socket对象 return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } public static Socket CreateUdpSocket() { // 创建一个基于UDP协议的Socket对象 return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } public static IPEndPoint GetLocalPoint(TcpListener tcpListener) { // 获取TcpListener对象的本地终结点 return (IPEndPoint)tcpListener.LocalEndpoint; } public static string GetLocalPoint_IP(TcpListener tcpListener) { // 获取TcpListener对象的本地终结点的IP地址 IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint; return localEndPoint.Address.ToString(); } public static int GetLocalPoint_Port(TcpListener tcpListener) { // 获取TcpListener对象的本地终结点的端口号 IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint; return localEndPoint.Port; } public static IPEndPoint GetLocalPoint(Socket NetSocket) { // 获取Socket对象的本地终结点 return (IPEndPoint)NetSocket.LocalEndPoint; } public static string GetLocalPoint_IP(Socket NetSocket) { // 获取Socket对象的本地终结点的IP地址 IPEndPoint localEndPoint = (IPEndPoint)NetSocket.LocalEndPoint; return localEndPoint.Address.ToString(); } public static int GetLocalPoint_Port(Socket NetSocket) { // 获取Socket对象的本地终结点的端口号 IPEndPoint localEndPoint = (IPEndPoint)NetSocket.LocalEndPoint; return localEndPoint.Port; } public static void BindEndPoint(Socket NetSocket, IPEndPoint endPoint) { // 绑定终结点 if (!NetSocket.IsBound) { NetSocket.Bind(endPoint); } } public static void BindEndPoint(Socket NetSocket, string NetIP, int NetPort) { //创建终结点 IPEndPoint endPoint = CreateIPEndPoint(NetIP, NetPort); //绑定终结点 if (!NetSocket.IsBound) { NetSocket.Bind(endPoint); } } public static void StartListen(Socket NetSocket, int NetPort) { //创建本地终结点 IPEndPoint localPoint = CreateIPEndPoint(InternetProHelper.LocalHostName, NetPort); //绑定到本地终结点 BindEndPoint(NetSocket, localPoint); //开始监听 NetSocket.Listen(200); } public static void StartListen(Socket NetSocket, int NetPort, int maxConnection) { //创建本地终结点 IPEndPoint localPoint = CreateIPEndPoint(InternetProHelper.LocalHostName, NetPort); //绑定到本地终结点 BindEndPoint(NetSocket, localPoint); //开始监听 NetSocket.Listen(maxConnection); } public static void StartListen(Socket NetSocket, string NetIP, int NetPort, int maxConnection) { //绑定到本地终结点 BindEndPoint(NetSocket, NetIP, NetPort); //开始监听 NetSocket.Listen(maxConnection); } public static bool Connect(Socket NetSocket, string NetIP, int NetPort) { // 连接到基于TCP协议的服务器,连接成功返回true,否则返回false try { //连接服务器 NetSocket.Connect(NetIP, NetPort); //检测连接状态 return NetSocket.Poll(-1, SelectMode.SelectWrite); } catch (SocketException ex) { throw new Exception(ex.Message); } } // 以同步方式向指定的Socket对象发送消息 public static void SendMsg(Socket NetSocket, byte[] dataStr) { //发送消息 NetSocket.Send(dataStr, dataStr.Length, SocketFlags.None); } // 使用UTF8编码格式以同步方式向指定的Socket对象发送消息 public static void SendMsg(Socket NetSocket, string dataStr) { //将字符串消息转换成字符数组 byte[] NetBuf = System.Text.Encoding.UTF8.GetBytes(dataStr); //发送消息 NetSocket.Send(NetBuf, NetBuf.Length, SocketFlags.None); } // 以同步方式接收消息 public static void ReceiveMsg(Socket NetSocket, byte[] NetBuf) { NetSocket.Receive(NetBuf); } // 以同步方式接收消息 public static string ReceiveMsg(Socket NetSocket) { //定义接收缓冲区 byte[] NetBuf = new byte[10000]; //接收数据,获取接收到的字节数 int RecvNum = NetSocket.Receive(NetBuf); //定义临时缓冲区 byte[] DataBuf = new byte[RecvNum]; //将接收到的数据写入临时缓冲区 Buffer.BlockCopy(NetBuf, 0, DataBuf, 0, RecvNum); //对DataBuf进行处理 return Convert.ToString(DataBuf); } // 关闭基于Tcp协议的Socket对象 public static void Close(Socket NetSocket) { try { //禁止Socket对象接收和发送数据 NetSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { throw ex; } finally { //关闭Socket对象 NetSocket.Close(); } } }}


总结

本文到此为止。希望能帮到你,也希望你能多多关注源搜网的更多内容!


0

精彩评论

暂无评论...
验证码 换一张
取 消