siso

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));
                           }
                       }
 

 

 

分类:

技术点:

相关文章:

  • 2021-11-18
  • 2019-10-11
  • 2022-12-23
  • 2022-02-01
  • 2022-02-08
  • 2022-12-25
  • 2021-07-05
  • 2022-12-23
猜你喜欢
  • 2022-02-18
  • 2021-06-28
  • 2021-12-31
  • 2022-01-28
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案