C# 为什么我用异步UDP客户端套接字随机收到UDP套接字应答?

C# 为什么我用异步UDP客户端套接字随机收到UDP套接字应答?,c#,asynchronous,udpclient,C#,Asynchronous,Udpclient,我有一个代码,在那里发送一个XML文件到一个UdpSocket并收到一个答案。我异步发送和接收答案。我的问题是,当我从UDP套接字收到答案时,我无法将其保存到正确的文件中。我试过很多东西,但都不管用 简短地解释我的代码。我开始在Main()方法中创建3个异步连接。它调用静态void AsynchronousConnection(objectobjectfilename),从那里我调用UdpStartClient方法 通过UdpStartClient方法,我发送一个带有UdpSendXmlFile

我有一个代码,在那里发送一个XML文件到一个UdpSocket并收到一个答案。我异步发送和接收答案。我的问题是,当我从UDP套接字收到答案时,我无法将其保存到正确的文件中。我试过很多东西,但都不管用

简短地解释我的代码。我开始在Main()方法中创建3个异步连接。它调用静态void AsynchronousConnection(objectobjectfilename),从那里我调用UdpStartClient方法

通过UdpStartClient方法,我发送一个带有UdpSendXmlFile的文件(fileToSend、udpClient、bytes、CallDuration、out-threadId)

在那之后,我通过udprecivedxmlfile方法(c:\received“+filename,udpClient,remoteEPReceived,CallDuration,out-threadId)在while循环中收到了答案

我在udprecivedxmlfile方法中收到的答案将保存到一个文件中。这就是我的问题所在,我想。我通过异步连接发送了3个文件,并从UDP套接字收到了3个应答,但应答与我发送的文件不匹配

例如,我发送这3个文件

MessagingText4000.xml

MessagingText4001.xml

MessagingText8.xml

我随机收到了答案,例如:

文件MessagingText4000.xml可以从MessagingText8.xml获得答案

文件MessagingText4001.xml可以从MessagingText4000.xml获得答案

文件MessagingText8.xml可以从MessagingText4001.xml获得答案

你能帮我吗,这样我就得到了正确答案的正确文件


公共委托void asynchmethodcall(对象objectFilename、int callDuration、out int threadId、out string receivedXmlDataFromTNX)

//程序
公共静态void Main(字符串[]args)
{
新线程;
newThread=新线程(异步连接);
newThread.Name=“4001”;
Start(“MessagingText4001.xml”);
newThread=新线程(异步连接);
newThread.Name=“4000”;
Start(“MessagingText4000.xml”);
newThread=新线程(异步连接);
newThread.Name=“8”;
Start(“MessagingText8.xml”);
}
//异步连接
静态无效异步连接(对象objectFilename)
{
int threadId;字符串receivedXmlData;
UdpClass UdpClass=新的UdpClass();
AsyncMethodCaller=新的AsyncMethodCall(udpClass.UdpStartClient);
IAsyncResult result=caller.BeginInvoke(objectFilename,500,out-threadId,out-receivedXmlData,null,null);
result.AsyncWaitHandle.WaitOne();
EndInvoke(out threadId、out receivedXmlData、result);
result.AsyncWaitHandle.Close();
}
//已收到UDP客户端
void udprecivedxmlfile(对象对象objectFilename、UdpClient UdpClient、IPEndPoint remoteEPReceived、int CallDuration、out int threadId)
{
睡眠(CallDuration);
threadId=Thread.CurrentThread.ManagedThreadId;
尝试
{
//阻止,直到远程主机在此套接字上返回消息。
Byte[]receiveBytes=udpClient.Receive(ref remoteEPReceived);
File.writealText((string)objectFilename,Encoding.UTF8.GetString(receiveBytes));
}
捕获(例外情况除外)
{
Console.WriteLine(“在udprecivedxmlfile:\n“+ex.ToString())中遇到此错误,请与网站管理员联系”;
}
}
//UDP客户端发送
void UdpSendXmlFile(字符串fileToSend,UdpClient UdpClient,字节[]字节,int CallDuration,out int threadId)
{
睡眠(CallDuration);
threadId=Thread.CurrentThread.ManagedThreadId;
尝试
{
//将数据字符串编码为字节数组
XmlDocument xmlDoc=新的XmlDocument();
加载(fileToSend);
//加载XML文件
字符串xmlContent=xmlDoc.OuterXml;
byte[]msg=Encoding.UTF8.GetBytes(xmlDoc.OuterXml);
//通过套接字发送数据。
udpClient.Send(消息,消息长度);
}
捕获(例外情况除外)
{Console.WriteLine(“在UdpSendXmlFile:\n“+ex.ToString())中遇到此错误,请与网站管理员联系”;
}
}
//UdpStart客户端
public void UdpStartClient(对象objectFilename、int CallDuration、out int threadId、out string receivedXmlData)
{
字符串文件名=(字符串)objectFilename;
receivedXmlData=null;Thread.Sleep(CallDuration);
threadId=Thread.CurrentThread.ManagedThreadId;
尝试
{
WriteLine(“1:UdpStartClient Async-id:+threadId+”objectFilename:+(string)objectFilename);
fileToSend=fileLocation+filename;
//将文件发送到UdpSocket
UdpSendXmlFile(fileToSend、udpClient、bytes、CallDuration、out-threadId);
TimeSpan maxTime=TimeSpan.FromSeconds(10);
秒表秒表=Stopwatch.StartNew();
bool stopwatchStop=false;
while(stopwatch.appeased

UDP就是这样工作的

UDP是一种协议,在连接到IP网络的设备之间提供不可靠、无序的数据传输。它通常被认为是OSI堆栈中的“第4层”协议。UDP的一个流行用途是传输时间敏感信息,如IP语音。RFC 7中指定了UDP
// Program
public static void Main(String[] args)
{
  Thread newThread;
  newThread = new Thread(AsynchronousConnection);
  newThread.Name = "4001";
  newThread.Start("MessagingText4001.xml");

  newThread = new Thread(AsynchronousConnection);
  newThread.Name = "4000";
  newThread.Start("MessagingText4000.xml");

  newThread = new Thread(AsynchronousConnection);
  newThread.Name = "8";
  newThread.Start("MessagingText8.xml");
}


// Asynchronous Connection 
static void AsynchronousConnection(object objectFilename)
{
  int threadId; string receivedXmlData;
  UdpClass udpClass = new UdpClass();
  AsyncMethodCall caller = new AsyncMethodCall(udpClass.UdpStartClient);
  IAsyncResult result = caller.BeginInvoke(objectFilename, 500, out threadId, out receivedXmlData, null, null);
  result.AsyncWaitHandle.WaitOne();
  caller.EndInvoke(out threadId, out receivedXmlData, result);
  result.AsyncWaitHandle.Close();
}


// UdpClient received 
void UdpReceivedXmlFile(object objectFilename, UdpClient udpClient, IPEndPoint remoteEPReceived, int CallDuration, out int threadId)
{
  Thread.Sleep(CallDuration);
  threadId = Thread.CurrentThread.ManagedThreadId;
  try
  {
    // Blocks until a message returns on this socket from a remote host. 
    Byte[] receiveBytes = udpClient.Receive(ref remoteEPReceived);
    File.WriteAllText((string)objectFilename, Encoding.UTF8.GetString(receiveBytes));
  }
  catch (Exception ex)
  {
    Console.WriteLine("Contact webmaster with this error in UdpReceivedXmlFile:\n " + ex.ToString());
  }
}


// UdpClient send 
void UdpSendXmlFile(string fileToSend, UdpClient udpClient, byte[] bytes, int CallDuration, out int threadId)
{
  Thread.Sleep(CallDuration);
  threadId = Thread.CurrentThread.ManagedThreadId;
  try
  {
    // Encode the data string into a byte array 
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(fileToSend);
    // Load XML fil
    string xmlContent = xmlDoc.OuterXml;
    byte[] msg = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);
    // Send the data through the socket.
    udpClient.Send(msg, msg.Length);
  }
  catch (Exception ex)
  { Console.WriteLine("Contact webmaster with this error in UdpSendXmlFile:\n " + ex.ToString()); 
  }
}


// UdpStart Client
public void UdpStartClient(object objectFilename, int CallDuration, out int threadId, out string receivedXmlData)
{
  string filename = (string)objectFilename;
  receivedXmlData = null; Thread.Sleep(CallDuration);
  threadId = Thread.CurrentThread.ManagedThreadId;
  try
  {
    Console.WriteLine("1: UdpStartClient Async - id: " + threadId + " objectFilename: " + (string)objectFilename);
    fileToSend = fileLocation + filename;
    // Send a file to the UdpSocket 
    UdpSendXmlFile(fileToSend, udpClient, bytes, CallDuration, out threadId);

    TimeSpan maxTime = TimeSpan.FromSeconds(10);
    Stopwatch stopwatch = Stopwatch.StartNew();
    bool stopwatchStop = false;

    while (stopwatch.Elapsed < maxTime && !stopwatchStop)
    {
      // listed on UdpSocket and save to file 
      UdpReceivedXmlFileDirectToFile("c:\\Received" + filename, udpClient, remoteEPReceived, CallDuration, out threadId);
      attributXMLReceived = ReadXmlAttribut("c:\\Received" + filename, CallDuration, out threadId);

      if ((attributXMLReceived == "Status=Pending") || (attributXMLReceived == "Status=Sent"))
      {
        Console.WriteLine("Answer from XMl file:" + attributXMLReceived + " id: " + Thread.CurrentThread.ManagedThreadId + "\n");
      }
      else if (attributXMLReceived == "Status=Delivered")
      {
        Console.WriteLine("Answer from XMl file:" + attributXMLReceived + " id: " + Thread.CurrentThread.ManagedThreadId + "\n");
        stopwatchStop = true;
      }
      if (stopwatch.Elapsed == maxTime)
        Console.WriteLine("Timeout!");
    }
  }
  catch (Exception e)
  {
    Console.WriteLine(e.ToString());
  }
}