C#基于Socket的网络通信类你了解吗

Mercia ·
更新时间:2024-11-10
· 63 次阅读

目录

摘要

代码

总结

摘要

之所以要进行Socket套接字通信库封装,主要是直接使用套接字进行网络通信编程相对复杂,特别对于初学者而言。实际上微软从.net 2.0开始已经提供了TCP、UDP通信高级封装类如下:

TcpListener TcpClient UdpClient

微软从.net 4.0开始提供基于Task任务的异步通信接口。而直接使用socket封装库,很多socket本身的细节没办法自行控制,本文目就是提供一种socket的封装供参考。文中展示部分封装了TCP通信库,UDP封装也可触类旁通:

CusTcpListener CusTcpClient 代码 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) < ushort.MinValue) || (Convert.ToInt32(NetPort) > 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 < 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(); } } } } 总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注软件开发网的更多内容!



C# 通信 socket

需要 登录 后方可回复, 如果你还没有账号请 注册新账号