首页 > 其他 > 详细

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

时间:2014-04-29 01:06:16      阅读:1135      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
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();
       }
    }
}
bubuko.com,布布扣

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

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

改为下面就可以了:

bubuko.com,布布扣
if (socket.Poll(-1,SelectMode.SelectRead))
                       {                      
                           if ( ( dataLength = socket.Receive(buffer) ) > 0)
                           {
                               Analyer(Encoding.ASCII.GetString(buffer, 0, dataLength));
                           }
                       }
 
bubuko.com,布布扣

 

 

UDP 一个封锁操作被对 WSACancelBlockingCall 的调用中断,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/siso/p/3692512.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!