UDP 一个封锁操作被对 WSACancelBlockingCall 的调用中断

using System;

using System.Collections.Generic;

using System.Text;

using System.Net.Sockets;

using System.Net;

using Common;

using System.Threading;

using System.IO;

 

namespace BLL

{

   public class SocketControl

    {

       bool isRun = false;

       Socket socket;

       IPEndPoint ipEndPoint;

       Thread threadListen ;

       byte[] buffer = new byte[1024];  

 

       private void Init()

       {

           ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), ConfigInformation.UdpPort);

           socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

           socket.Bind(ipEndPoint);   

         

       }

 

       public void Start()

       {

           Init();

           isRun = true;

           threadListen = new Thread(Listen);

           threadListen.Start();         

       }

 

       private void Listen()

       {

          int dataLength ;

 

           while (isRun)

               {

                   try

                   {

                                            

                           if ( ( dataLength = socket.Receive(buffer) ) > 0)

                           {

                               Analyer(Encoding.ASCII.GetString(buffer, 0, dataLength));

                           }

                      

                   }

                   catch(Exception ex)

                   {

                       Helper.LogWrite(ex.Message);

                   }    

               } 

       }

 

       private void Analyer(string data)

       {

           if (data == "LoadPlan")

           {

               PlanControl.LoadPlan(ConfigInformation.PlanConfigPath);

           }

       }

 

       public void Stop()

       {   

           isRun = false;

           socket.Shutdown(SocketShutdown.Both);

           socket.Close();

       }

    }

}

当执行Stop时出现提示:一个封锁操作被对 WSACancelBlockingCall 的调用中断。

后经网上查找,原因大概是因为你关闭socket时,socket.Receive(buffer); 仍出于读取状态。

改为下面就可以了:

if (socket.Poll(-1,SelectMode.SelectRead))

                       {                      

                           if ( ( dataLength = socket.Receive(buffer) ) > 0)

                           {

                               Analyer(Encoding.ASCII.GetString(buffer, 0, dataLength));

                           }

                       }

 

 

 

你可能感兴趣的:(cancel)