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

     

  • 相关阅读:
    根据用户行为发送客服消息
    tp5链接访问
    统计每天分享次数总和
    csv中文乱码
    Jupyter Notebook命令
    Laplace(拉普拉斯)算子
    Sobel算子
    Opencv图像连通域
    Opencv常用函数讲解
    12306 Pytho抢票代码
  • 原文地址:https://www.cnblogs.com/siso/p/3692512.html
Copyright © 2020-2023  润新知