UDP异步通信
思想是:点击连接按钮,开始接收数据并保存;点击断开按钮不在接收数据并停止保存数据。
现在的问题是:第一次运行,点击连接按钮,开始收数并保存,点击断开按钮则停止。这时再点击连接时,语句运行到udpFB_M.BeginReceive(ReceiveCallback1, sUdpReceive_M);但是没有进入ReceiveCallback1,再点击助手发一组数据也没有触发这个委托。
没有想明白,请各路朋友帮忙分析一下,部分代码如下。
IPAddress host = IPAddress.Parse(_ctrlHost_M);
IPEndPoint remoteIpEndPoint1 = new IPEndPoint(IPAddress.Any, 0);
udpFB_M = new UdpClient(Convert.ToInt32(_ctrlLocalPort));
sUdpReceive_M = new UdpState
{
e = remoteIpEndPoint1,
u = udpFB_M
};
udpFB_M.BeginReceive(ReceiveCallback1, sUdpReceive_M);
private void ReceiveCallback1(IAsyncResult ar)
{
try
{
if (ar.AsyncState is UdpState ss)
{
UdpClient udpClient1 = ss.u;
IPEndPoint ip1 = ss.e;
byte[] receiveBytes_M = udpClient1.EndReceive(ar, ref ip1);
byte[] temp_fb = new byte[receiveBytes_M.Length];
Array.Copy(receiveBytes_M, 0, temp_fb, 0, temp_fb.Length);
string tempstr1 = "";
tempstr1 = byteToHexStr(temp_fb);
sw.WriteLine(tempstr1);
sw.Flush();
}
}
catch (Exception)
{
//处理异常
}
}
在byte[] receiveBytes_M = udpClient1.EndReceive(ar, ref ip1);后面加上以下代码:
udpClient1.
BeginReceive(ReceiveCallback1, ss);
代表继续接收
感谢楼上的提醒,我更新一下程序,还是同样的问题
IPAddress host = IPAddress.Parse(_ctrlHost_M);
IPEndPoint remoteIpEndPoint1 = new IPEndPoint(IPAddress.Any, 0);
udpFB_M = new UdpClient(Convert.ToInt32(_ctrlLocalPort));
sUdpReceive_M = new UdpState
{
e = remoteIpEndPoint1,
u = udpFB_M
};
udpFB_M.BeginReceive(ReceiveCallback1, sUdpReceive_M);
private void ReceiveCallback1(IAsyncResult ar)
{
try
{
if (ar.AsyncState is UdpState ss)
{
UdpClient udpClient1 = ss.u;
IPEndPoint ip1 = ss.e;
byte[] receiveBytes_M = udpClient1.EndReceive(ar, ref ip1);
byte[] temp_fb = new byte[receiveBytes_M.Length];
Array.Copy(receiveBytes_M, 0, temp_fb, 0, temp_fb.Length);
string tempstr1 = "";
tempstr1 = byteToHexStr(temp_fb);
sw.WriteLine(tempstr1);
sw.Flush();
udpFB_M.BeginReceive(ReceiveCallback1, sUdpReceive_M);
}
}
catch (Exception)
{
//处理异常
}
}
ReceiveCallback1中重新接收数据改下面的试试。去掉try..catch看下是不是try语句块有问题导致没有执行BeginReceive语句
udpFB_M.BeginReceive(ReceiveCallback1, sUdpReceive_M);
==>
udpFB_M.BeginReceive(ReceiveCallback1, ss);