异步Socket通信总结

本文详细介绍了使用C#实现的异步Socket通信过程,包括侦听、接受、接收和发送数据的回调函数,以及状态对象的使用,确保了在并发环境下的正确通信。通过示例代码展示了如何建立和断开连接,以及信息的完整传输和接收确认。
摘要由CSDN通过智能技术生成

前面已经贴了Socket的基本编程要点和步骤,这里继续贴一下关于异步Socket通信的代码。

服务端(异步)

using System.Net ;

using System.Net.Sockets ;

using System.IO ;

using System.Text ;

using System.Threading ;

 

 

         public static ManualResetEvent allDone = new ManualResetEvent(false);     

         private Thread th;

         private bool listenerRun = true ;

         Socket listener;

         private const int MAX_SOCKET=10;

         protected override void Dispose( bool disposing )

         {

              try

              {

                   listenerRun = false ;

                   th.Abort ( ) ;

                   th = null ;

                   listener.Close();

              }

              catch { }             

         }

         //得到本机IP地址

         //得到本机IP地址

         public static IPAddress GetServerIP()

         {

              IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());

              return ieh.AddressList[0];

         }

         //侦听方法

         private void Listen()

         {

              try

              {

                   int nPort=int.Parse(this.txtLocalPort.Text);

                   IPAddress ServerIp=GetServerIP();

                   IPEndPoint iep=new IPEndPoint(ServerIp,nPort);

                   listener=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

             

                   listener.Bind(iep);

                   listener.Listen(10);

                   statusBar1.Panels[0].Text ="端口:"+this.txtLocalPort.Text+"正在监听......";

 

 

                   while(listenerRun)

                   {                           

                       allDone.Reset();

                       listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);

                       allDone.WaitOne();                  

                   }

              }

              catch (System.Security.SecurityException )

              {

                   MessageBox.Show ("防火墙安全错误!","错误",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);

              }

         }

 

 

         //异步回调函数

         public void AcceptCallback(IAsyncResult ar)

         {             

              Socket listener = (Socket)ar.AsyncState;

              Socket client=listener.EndAccept(ar) ;

              allDone.Set();

              StateObject state = new StateObject();

              state.workSocket = client;

 

 

              //远端信息

              EndPoint tempRemoteEP = client.RemoteEndPoint;

              IPEndPoint tempRemoteIP = ( IPEndPoint )tempRemoteEP ;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值