最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#基于Socket套接字的網(wǎng)絡(luò)通信封裝

 更新時(shí)間:2021年11月25日 15:03:01   作者:uiuan00  
這篇文章主要為大家詳細(xì)介紹了C#基于Socket套接字的網(wǎng)絡(luò)通信封裝本文實(shí)例為大家分享了Java實(shí)現(xiàn)圖片旋轉(zhuǎn)的具體代碼,供大家參考,具體內(nèi)容如下

本文為大家分享了C#基于Socket套接字的網(wǎng)絡(luò)通信封裝代碼,供大家參考,具體內(nèi)容如下

摘要

之所以要進(jìn)行Socket套接字通信庫(kù)封裝,主要是直接使用套接字進(jìn)行網(wǎng)絡(luò)通信編程相對(duì)復(fù)雜,特別對(duì)于初學(xué)者而言。實(shí)際上微軟從.net 2.0開始已經(jīng)提供了TCP、UDP通信高級(jí)封裝類如下:

TcpListener
TcpClient
UdpClient

微軟從.net 4.0開始提供基于Task任務(wù)的異步通信接口。而直接使用socket封裝庫(kù),很多socket本身的細(xì)節(jié)沒(méi)辦法自行控制,本文目就是提供一種socket的封裝供參考。文中展示部分封裝了TCP通信庫(kù),UDP封裝也可觸類旁通:

CusTcpListener
CusTcpClient

TCP服務(wù)端

TCP服務(wù)端封裝了服務(wù)端本地綁定、監(jiān)聽(tīng)、接受客戶端連接,并提供了網(wǎng)絡(luò)數(shù)據(jù)流的接口。完整代碼:

public class CusTcpListener
    {
        private IPEndPoint mServerSocketEndPoint;
        private Socket mServerSocket;
        private bool isActive;
 
        public Socket Server
        {
            get { return this.mServerSocket; }
        }
        protected bool Active
        {
            get { return this.isActive; }
        }
        public EndPoint LocalEndpoint
        {
            get
            {
                if (!this.isActive)
                {
                    return this.mServerSocketEndPoint;
                }
                return this.mServerSocket.LocalEndPoint;
            }
        }
        public NetworkStream DataStream
        {
            get
            {
                NetworkStream networkStream = null;
                if (this.Server.Connected)
                {
                    networkStream = new NetworkStream(this.Server, true);
                }
                return networkStream;
            }
        }
 
        public CusTcpListener(IPEndPoint localEP)
        {
            this.mServerSocketEndPoint = localEP;
            this.mServerSocket = new Socket(this.mServerSocketEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        }
 
        public CusTcpListener(string localaddr, int port)
        {
            if (localaddr == null)
            {
                throw new ArgumentNullException("localaddr");
            }
            this.mServerSocketEndPoint = new IPEndPoint(IPAddress.Parse(localaddr), port);
            this.mServerSocket = new Socket(this.mServerSocketEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        }
 
        public CusTcpListener(int port)
        {
            this.mServerSocketEndPoint = new IPEndPoint(IPAddress.Any, port);
            this.mServerSocket = new Socket(this.mServerSocketEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        }
 
        public void Start()
        {
            this.Start(int.MaxValue);
        }
        /// <summary>
        /// 開始服務(wù)器監(jiān)聽(tīng)
        /// </summary>
        /// <param name="backlog">同時(shí)等待連接的最大個(gè)數(shù)(半連接隊(duì)列個(gè)數(shù)限制)</param>
        public void Start(int backlog)
        {
            if (backlog > int.MaxValue || backlog < 0)
            {
                throw new ArgumentOutOfRangeException("backlog");
            }
            if (this.mServerSocket == null)
            {
                throw new NullReferenceException("套接字為空");
            }
            this.mServerSocket.Bind(this.mServerSocketEndPoint);
            this.mServerSocket.Listen(backlog);
            this.isActive = true;
        }
        public void Stop()
        {
            if (this.mServerSocket != null)
            {
                this.mServerSocket.Close();
                this.mServerSocket = null;
            }
            this.isActive = false;
            this.mServerSocket = new Socket(this.mServerSocketEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        }
 
        public Socket AcceptSocket()
        {
            Socket socket = this.mServerSocket.Accept();
            return socket;
        }
 
        public CusTcpClient AcceptTcpClient()
        {
            CusTcpClient tcpClient = new CusTcpClient(this.mServerSocket.Accept());
            return tcpClient;
        }
    }

TCP客戶端

TCP客戶端封裝了客戶端本地綁定、連接服務(wù)器,并提供了網(wǎng)絡(luò)數(shù)據(jù)流的接口。完整代碼:

public class CusTcpClient : IDisposable
    {
        public Socket Client { get; set; }
        protected bool Active { get; set; }
        public IPEndPoint ClientSocketEndPoint { get; set; }
        public bool IsConnected { get { return this.Client.Connected; } }
        public NetworkStream DataStream
        {
            get
            {
                NetworkStream networkStream = null;
                if (this.Client.Connected)
                {
                    networkStream = new NetworkStream(this.Client, true);
                }
                return networkStream;
            }
        }
 
        public CusTcpClient(IPEndPoint localEP)
        {
            if (localEP == null)
            {
                throw new ArgumentNullException("localEP");
            }
            this.Client = new Socket(localEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            this.Active = false;
            this.Client.Bind(localEP);
            this.ClientSocketEndPoint = localEP;
        }
 
        public CusTcpClient(string localaddr, int port)
        {
            if (localaddr == null)
            {
                throw new ArgumentNullException("localaddr");
            }
            IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(localaddr), port);
            this.Client = new Socket(localEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            this.Active = false;
            this.Client.Bind(localEP);
            this.ClientSocketEndPoint = localEP;
        }
        internal CusTcpClient(Socket acceptedSocket)
        {
            this.Client = acceptedSocket;
            this.Active = true;
            this.ClientSocketEndPoint = (IPEndPoint)this.Client.LocalEndPoint;
        }
 
        public void Connect(string address, int port)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(address), port);
            this.Connect(remoteEP);
        }
 
        public void Connect(IPEndPoint remoteEP)
        {
            if (remoteEP == null)
            {
                throw new ArgumentNullException("remoteEP");
            }
            this.Client.Connect(remoteEP);
            this.Active = true;
        }
 
        public void Close()
        {
            this.Dispose(true);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                IDisposable dataStream = this.DataStream;
                if (dataStream != null)
                {
                    dataStream.Dispose();
                }
                else
                {
                    Socket client = this.Client;
                    if (client != null)
                    {
                        client.Close();
                        this.Client = null;
                    }
                }
                GC.SuppressFinalize(this);
            }
        }
 
        public void Dispose()
        {
            this.Dispose(true);
        }
    }

通信實(shí)驗(yàn)

控制臺(tái)程序試驗(yàn),服務(wù)端程序:

class Program
    {
        static void Main(string[] args)
        {
            Thread listenerThread = new Thread(ListenerClientConnection);
            listenerThread.IsBackground = true;
            listenerThread.Start();
 
            Console.ReadKey();
        }
 
        private static void ListenerClientConnection()
        {
            CusTcpListener tcpListener = new CusTcpListener("127.0.0.1", 5100);
            tcpListener.Start();
            Console.WriteLine("等待客戶端連接……");
            while (true)
            {
                CusTcpClient tcpClient = tcpListener.AcceptTcpClient();
 
                Console.WriteLine("客戶端接入,ip={0} port={1}",
                    tcpClient.ClientSocketEndPoint.Address, tcpClient.ClientSocketEndPoint.Port);
                Thread thread = new Thread(DataHandleProcess);
                thread.IsBackground = true;
                thread.Start(tcpClient);
            }
        }
 
        private static void DataHandleProcess(object obj)
        {
            CusTcpClient tcpClient = (CusTcpClient)obj;
            StreamReader streamReader = new StreamReader(tcpClient.DataStream, Encoding.Default);
            Console.WriteLine("等待客戶端輸入:");
            while (true)
            {
                try
                {
                    string receStr = streamReader.ReadLine();
                    Console.WriteLine(receStr);
                }
                catch (Exception)
                {
                    Console.WriteLine("斷開連接");
                    break;
                }
                Thread.Sleep(5);
            }
        }
    }

客戶端程序:

class Program
    {
        static void Main(string[] args)
        {
            Thread listenerThread = new Thread(UserProcess);
            listenerThread.IsBackground = true;
            listenerThread.Start();
 
            Console.ReadKey();
        }
 
        private static void UserProcess()
        {
            Console.WriteLine("連接服務(wù)器");
            CusTcpClient tcpClient = new CusTcpClient("127.0.0.1", 5080);
            tcpClient.Connect("127.0.0.1", 5100);
 
            Console.WriteLine("開始和服務(wù)器通信");
            StreamWriter sw = new StreamWriter(tcpClient.DataStream, Encoding.Default);
            sw.AutoFlush = true;
            while (true)
            {
                for (int i = 0; i < 10; i++)
                {
                    string str = string.Format("第{0}次,內(nèi)容:{1}", i, "測(cè)試通信");
                    Console.WriteLine("發(fā)送數(shù)據(jù):{0}", str);
                    sw.WriteLine(str);
                }
                break;
            }
        }
    }

通信成功:

通過(guò)本次封裝演示可實(shí)現(xiàn)基于Socket的通信庫(kù)封裝,目的就是使用Socket通信庫(kù)讓應(yīng)用開發(fā)人員在進(jìn)行網(wǎng)絡(luò)通訊編程時(shí)無(wú)需關(guān)心底層通訊機(jī)制,而只關(guān)心應(yīng)用層的開發(fā),讓開發(fā)變得更簡(jiǎn)潔。當(dāng)然UDP封裝類似,可自行設(shè)計(jì)。當(dāng)然本文只是一種示例,實(shí)際使用可使用.net自帶封裝庫(kù)或自定義封裝。

補(bǔ)充:目前有很多優(yōu)秀的開源Socket框架,比如SuperSocketFastSocket等。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • C#實(shí)現(xiàn)的最短路徑分析

    C#實(shí)現(xiàn)的最短路徑分析

    C#實(shí)現(xiàn)的最短路徑分析,需要的朋友可以參考一下
    2013-03-03
  • C#中獲取各種文件名的實(shí)現(xiàn)方式

    C#中獲取各種文件名的實(shí)現(xiàn)方式

    這篇文章主要介紹了C#中獲取各種文件名的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • C# GetField方法的應(yīng)用實(shí)例講解

    C# GetField方法的應(yīng)用實(shí)例講解

    C#中的GetField是一個(gè)反射方法,用于獲取指定類型的字段信息,它可以通過(guò)字段名稱來(lái)獲取字段對(duì)象,并且可以在運(yùn)行時(shí)動(dòng)態(tài)地訪問(wèn)和操作這些字段,本文給大家介紹了C# GetField方法的應(yīng)用,需要的朋友可以參考下
    2024-04-04
  • 在C#程序中注入惡意DLL的方法詳解

    在C#程序中注入惡意DLL的方法詳解

    為什么?Windbg?附加到?C#?程序后,程序就處于中斷狀態(tài)了?它到底是如何實(shí)現(xiàn)的?其實(shí)簡(jiǎn)而言之就是線程的遠(yuǎn)程注入,這一篇就展開說(shuō)一下
    2022-09-09
  • TortoiseSVN使用教程

    TortoiseSVN使用教程

    TortoiseSVN 是 Subversion 版本控制系統(tǒng)的一個(gè)免費(fèi)開源客戶端,可以超越時(shí)間的管理文件和目錄。本文給大家介紹TortoiseSVN使用教程,對(duì)tortoisesvn使用相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧
    2015-12-12
  • C#訪問(wèn)及調(diào)用類中私有成員與方法示例代碼

    C#訪問(wèn)及調(diào)用類中私有成員與方法示例代碼

    訪問(wèn)一個(gè)類的私有成員不是什么好做法,大家也都知道私有成員在外部是不能被訪問(wèn)的,這篇文章主要給大家介紹了關(guān)于C#訪問(wèn)及調(diào)用類中私有成員與方法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2018-06-06
  • c#語(yǔ)言程序構(gòu)建基塊

    c#語(yǔ)言程序構(gòu)建基塊

    這篇文章主要介紹了c#語(yǔ)言程序構(gòu)建基塊,關(guān)于c#程序構(gòu)建基塊我們要從成員開始,class?的成員要么是靜態(tài)成員,要么是實(shí)例成員。?靜態(tài)成員屬于類,而實(shí)例成員則屬于對(duì)象,具體內(nèi)容需要的小伙伴可以參考下面文章的詳細(xì)內(nèi)容
    2021-12-12
  • C#中使用閉包與意想不到的坑詳解

    C#中使用閉包與意想不到的坑詳解

    這篇文章主要給大家介紹了關(guān)于C#中使用閉包與意想不到的坑,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用C#具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • C#使用Zxing.dll組件解析二維碼的實(shí)現(xiàn)

    C#使用Zxing.dll組件解析二維碼的實(shí)現(xiàn)

    ZXing是一個(gè)開源的,支持多種格式的條形碼圖像處理庫(kù),本文主要介紹了C#使用Zxing.dll組件解析二維碼的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-09-09
  • c# 重載WndProc,實(shí)現(xiàn)重寫“最小化”的實(shí)現(xiàn)方法

    c# 重載WndProc,實(shí)現(xiàn)重寫“最小化”的實(shí)現(xiàn)方法

    在做“亦歌桌面版”的時(shí)候,發(fā)現(xiàn)當(dāng)打開歌詞狀態(tài)下,用最小化隱藏窗體到托盤的話(如下code #1),在調(diào)出發(fā)現(xiàn)歌詞縮小了(雖然顯現(xiàn)的窗體大小跟剛才一樣),從這點(diǎn)看調(diào)用該方法其實(shí)窗體大小是改變了的(這個(gè)過(guò)程只是不可視而已)。
    2009-02-02

最新評(píng)論

石河子市| 合作市| 富蕴县| 大冶市| 天台县| 鹤庆县| 房产| 全南县| 随州市| 靖州| 安塞县| 米林县| 开阳县| 平凉市| 姜堰市| 丰都县| 辰溪县| 绵阳市| 湖州市| 鹤庆县| 新昌县| 梁山县| 六枝特区| 广元市| 离岛区| 丰顺县| 留坝县| 柳林县| 隆林| 广水市| 莱芜市| 江西省| 荣成市| 杨浦区| 绥德县| 翼城县| 资兴市| 唐河县| 罗田县| 涡阳县| 望江县|