实际上下面的代码运行良好。这里的问题是当没有人从服务器/接收器,upd服务器/接收器接收udp时。服务器将停止发送和接收udp
private void Form1_Load(object sender, EventArgs e)
{
int receiverPort = 54679;
UdpClient receiver = new UdpClient(receiverPort);
receiver.BeginReceive(DataReceived, receiver);
}
private void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 54679);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
try
{
Invoke((MethodInvoker)delegate
{
string _hexString = ByteArrayToString(receivedBytes).Replace(" ", "");
TextBox1.Text = _hexString;
string replay = "I got your message";
byte[] replayBinary = StringToByteArray(replay);
IPEndPoint replayIpAddress = receivedIpEndPoint;
c.Send(replayBinary, replayBinary.Length, replayIpAddress);
});
c.BeginReceive(DataReceived, ar.AsyncState);
}
catch { }
}