我正在使用 UDPClient 发送多播请求并接收来自网络上各种客户端的响应。我能够发送请求并得到响应,但是我得到的响应非常慢。需要 2-3 分钟才能得到所有客户端的响应。在我在 WireShark 中检查的网络上发送请求时,我只在测试程序中看到所有客户端的响应(以毫秒为单位)。这需要很多时间。谁能指导我可能会犯什么错误?以下是代码。请指导我。过去 2 天我一直被困在这个问题上。
public class Trinity_WSDiscovery : IDiscoveryService
{
#region IDiscoveryService Members
public event EventHandler FoundNewDevice;
public event EventHandler EndOfDiscovery;
DeviceBinding m_DeviceBinding;
bool IsFindComplete = false;
Thread receiveThread;
UdpClient sock ;
IPEndPoint RemoteIpEndPoint = new IPEndPoint(System.Net.IPAddress.Any, 0);
IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Parse("239.255.255.250"), 3702);
UdpState udpState = new UdpState();
XmlDocument xmlDoc = new XmlDocument();
public void Start()
{
//Need to create new object every time we start discovery because
//every time udp buffer needs to be flushed and restarted
sock = new UdpClient();
string str = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:d=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\" xmlns:wsadis=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:dn=\"http://www.onvif.org/ver10/network/wsdl\"><soap:Header><wsadis:MessageID>uuid:" + System.Guid.NewGuid().ToString() + "</wsadis:MessageID><wsadis:To>urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsadis:To><wsadis:Action>http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</wsadis:Action></soap:Header><soap:Body><d:Probe><d:Types /> <d:Scopes/></d:Probe></soap:Body></soap:Envelope>";
byte[] data = Encoding.ASCII.GetBytes(str);
sock.Send(data, data.Length, iep);
sock.JoinMulticastGroup(System.Net.IPAddress.Parse("239.255.255.250"));
IPEndPoint iep1 = new IPEndPoint(System.Net.IPAddress.Any, 0);
udpState.ipEndpt = RemoteIpEndPoint;
udpState.udpClient = sock;
BeginReceive();
}
public void BeginReceive()
{
Thread.Sleep(100);
if (sock.Available > 0)
{
sock.BeginReceive(new AsyncCallback(ReceiveCallback), udpState);
}
else
{
FindComplete();
}
}
public void ReceiveCallback(IAsyncResult ar)
{
UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
IPEndPoint ipEndpt = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndpt;
Byte[] receiveBytes = udpClient.EndReceive(ar, ref ipEndpt);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
if (receiveString.Contains("NetworkVideoTransmitter"))
{
xmlDoc.LoadXml(receiveString);
XmlNodeList list = xmlDoc.GetElementsByTagName("XAddrs", "http://schemas.xmlsoap.org/ws/2005/04/discovery");
XmlNode node = list[0];
string strEndPoints = node.FirstChild.Value;
string[] strEndPointList = Regex.Split(strEndPoints, " ");
OnFoundDevice(strEndPointList);
}
BeginReceive();
}
}`
最佳答案
为什么需要 Thread.Sleep
?
它可能会导致延迟。
关于c# - UDPClient Async BeginReceive 很慢,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6027706/