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

时间:2021-04-19 21:30:15
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[]; 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) ) > )
{
Analyer(Encoding.ASCII.GetString(buffer, , 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(-,SelectMode.SelectRead))
{
if ( ( dataLength = socket.Receive(buffer) ) > )
{
Analyer(Encoding.ASCII.GetString(buffer, , dataLength));
}
}