首頁 > 軟體

C#基於Socket的網路通訊類你瞭解嗎

2022-03-29 13:01:19

摘要

之所以要進行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();
            }
        }
 
    }
}

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容!


IT145.com E-mail:sddin#qq.com