BeginReceive函数中的异步回调不起作用。
我的端口正在接收消息。但是我的代码无法接收和处理消息。
private void StartListening()
{
try
{
ar_ = udp.BeginReceive(Receive, new object());
}
catch(Exception ex)
{
}
}
private void Receive(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 7785);
byte[] bytes = udp.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
AppendTextBox("Received: " + string.Join("-", bytes) + Environment.NewLine);
}
public void Send(byte[] MsgBytes)
{
try
{
UdpClient client = new UdpClient();
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(txtbx_ip.Text), 7785);
client.Send(MsgBytes, MsgBytes.Length, ip);
client.Close();
AppendTextBox("Sent: " + string.Join("-", MsgBytes) + Environment.NewLine);
StartListening();
}
catch (Exception ex)
{
AppendTextBox("Exception occured: " + ex + Environment.NewLine);
}
}
在涉及BeginReceive之后,调试点再也不会碰到Receive函数。 另一个信息是,我在系统中使用静态IP。 (我不确定这是否是问题)。