当前位置: 首页 > 编程语言 > C#

基于Socket套接字的C#网络通信封装分享

时间:2023-04-10 18:14:49 C#

本文分享了C#Socket基于套接字的网络通信封装代码,供大家参考。具体内容如下Word通信库封装,主要是直接使用sockets进行网络通信编程比较复杂,特别适合初学者。实际上微软从.net2.0开始就提供了TCP和UDP通信的高级封装类如下:TcpListenerTcpClientUdpClient微软从.net4.0开始提供了基于任务的异步通信接口。但是直接使用socket封装库,socket本身的很多细节是无法自己控制的。本文的目的是提供一个socket包供参考。文中展示的部分封装了TCP通讯库,UDP封装也可以绕过:CusTcpListenerCusTcpClientTCPserverTCPserver封装了server本地绑定、监听、接受客户端连接,提供网络数据流的接口.完整代码:publicclassCusTcpListener{privateIPEndPointmServerSocketEndPoint;私有套接字mServerSocket;私人布尔是活跃的;公共套接字服务器{得到{返回this.mServerSocket;}}protectedboolActive{get{returnthis.isActive;}}publicEndPointLocalEndpoint{get{if(!this.isActive){returnthis.mServerSocketEndPoint;}返回this.mServerSocket.LocalEndPoint;}}publicNetworkStreamDataStream{get{NetworkStreamnetworkStream=null;如果(this.Server.Connected){networkStream=newNetworkStream(this.Server,true);}返回网络流;}}publicCusTcpListener(IPEndPointlocalEP){this.mServerSocketEndPoint=localEP;this.mServerSocket=newSocket(this.mServerSocketEndPoint.AddressFamily,SocketType.Stream,ProtocolType.Tcp);}publicCusTcpListener(stringlocaladdr,intport){if(localaddr==null){thrownewArgumentNullException("localaddr");}this.mServerSocketEndPoint=newIPEndPoint(IPAddress.Parse(localaddr),port);this.mServerSocket=newSocket(this.mServerSocketEndPoint.AddressFamily,SocketType.Stream,ProtocolType.Tcp);}publicCusTcpListener(intport){this.mServerSocketEndPoint=newIPEndPoint(IPAddress.Any,port);this.mServerSocket=newSocket(this.mServerSocketEndPoint.AddressFamily,SocketType.Stream,ProtocolType.Tcp);}民众voidStart(){this.Start(int.MaxValue);}///

///开始服务器监听//////同时等待的最大连接数(限制半连接数queues)publicvoidStart(intbacklog){if(backlog>int.MaxValue||backlog<0){thrownewArgumentOutOfRangeException("backlog");}if(this.mServerSocket==null){thrownewNullReferenceException("Thesocketisnull");}this.mServerSocket.Bind(this.mServerSocketEndPoint);this.mServerSocket.Listen(积压);this.isActive=true;}publicvoidStop(){if(this.mServerSocket!=null){this.mServerSocket.Close();this.mServerSocket=null;}this.isActive=false;this.mServerSocket=newSocket(this.mServerSocketEndPoint.AddressFamily,SocketType.Stream,ProtocolType.Tcp);}publicSocketAcceptSocket(){套接字套接字=this.mServerSocket.Accept();返回套接字;}publicCusTcpClientAccept(Ccp){CusTcpClienttcpClient=newCusTcpClient(this.mServerSocket.Accept());返回tcpClient;}}TCPclientTCPclient封装了客户端的本地绑定,连接服务端,提供网络数据流的接口完整代码:publicclassCusTcpClient:IDisposable{publicSocketClient{get;放;}protectedboolActive{get;放;}publicIPEndPointClientSocketEndPoint{get;放;}publicboolIsConnected{get{returnthis.Client.Connected;}}publicNetworkStreamDataStream{get{NetworkStreamnetworkStream=null;如果(this.Client.Connected){networkStream=newNetworkStream(this.Client,true);}返回网络流;}}publicCusTcpClient(IPEndPointlocalEP){if(localEP==null){thrownewArgumentNullException("localEP");}this.Client=newSocket(localEP.AddressFamily,SocketType.Stream,ProtocolType.Tcp);this.Active=false;这个.Client.Bind(本地EP);this.ClientSocketEndPoint=localEP;}publicCusTcpClient(stringlocaladdr,intport){if(localaddr==null){thrownewArgumentNullException("localaddr");}IPEndPointlocalEP=newIPEndPoint(IPAddress.Parse(localaddr),port);this.Client=newSocket(localEP.AddressFamily,SocketType.Stream,ProtocolType.Tcp);this.Active=false;this.Client.Bind(localEP);this.ClientSocketEndPoint=localEP;}internalCusTcpClient(SocketacceptedSocket){this.Client=acceptedSocket;这个。活动=真;this.ClientSocketEndPoint=(IPEndPoint)this.Client.LocalEndPoint;}publicvoidConnect(stringaddress,intport){if(address==null){thrownewArgumentNullException("address");}IPEndPointremoteEP=newIPEndPoint(IPAddress.Parse(address),port);this.Connect(remoteEP);}publicvoidConnect(IPEndPointremoteEP){if(remoteEP==null){thrownewArgumentNullException("remoteEP");}this.Client.Connect(remoteEP);this.Active=true;}publicvoidClose(){this.Dispose(true);}protectedvirtualvoidDispose(booldisposing){if(disposing){IDisposabledataStream=this.DataStream;if(dataStream!=null){dataStream.Dispose();}else{Socketclient=this.Client;if(client!=null){客户端t.关闭();this.Client=null;}}GC.SuppressFinalize(这个);}}publicvoidDispose(){this.Dispose(true);}}通信实验控制台程序测试,服务器程序:classProgram{staticvoidMain(string[]args){ThreadlistenerThread=newThread(ListenerClientConnection);listenerThread.IsBackground=true;listenerThread.Start();控制台.ReadKey();}privatestaticvoidListenerClientConnection(){CusTcpListenertcpListener=newCusTcpListener("127.0.0.1",5100);tcpListener.Start();Console.WriteLine("等待客户端连接...");while(true){CusTcpClienttcpClient=tcpListener.AcceptTcpClient();Console.WriteLine("客户端访问,ip={0}port={1}",tcpClientt.ClientSocketEndPoint.Address,tcpClient.ClientSocketEndPoint.Port);线程thread=newThread(DataHandleProcess);thread.IsBackground=true;thread.Start(tcpClient);}}privatestaticvoidDataHandleProcess(objectobj){CusTcpClienttcpClient=(CusTcpClient)obj;StreamReaderstreamReader=newStreamReader(tcpClient.DataStream,Encoding.Default);Console.WriteLine("等候客户终端输入:");while(true){try{stringreceStr=streamReader.ReadLine();控制台.WriteLine(receStr);}catch(Exception){Console.WriteLine("断开连接");休息;}Thread.Sleep(5);}}}客户端程序:classProgram{staticvoidMain(string[]args){ThreadlistenerThread=newThread(UserProcess);listenerThread.IsBackground=true;listenerThread.Start();控制台.ReadKey();}privatestaticvoidUserProcess(){Console.WriteLine("连接到服务器");CusTcpClienttcpClient=newCusTcpClient("127.0.0.1",5080);tcpClient.Connect("127.0.0.1",5100);Console.WriteLine("开始与服务器通信");StreamWritersw=newStreamWriter(tcpClient.DataStream,Encoding.Default);sw.AutoFlush=true;while(true){for(inti=0;i<10;i++){stringstr=string.Format("{0}time,content:{1}",i,"测试通信");Console.WriteLine("发送数据:{0}",str);sw.WriteLine(str);}休息;}}}通信成功:通过了这个封装演示可以实现基于Socket的通信库封装。目的是使用Socket通信库,让应用开发者在编写网络通信程序时无需关心底层通信机制,只关心应用层的开发,让开发更简洁。当然UDP的封装也是类似的,可以自己设计。当然,这篇文章只是一个例子。实际使用中,可以使用.net自带的包库,也可以自定义包。补充:目前有很多优秀的开源Socket框架,如SuperSocket、FastSocket等,本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: