我有一个创建 UDP 对象的表单,在 UDP 类中创建了一个 UDPClient,并使用 EndReceive 在 BeginReceive 方法中完成接收数据。
当我从 beginreceive 方法中打印接收数据的字符串后,将字节 [] 转换到控制台,并附加文本,只有接收到的数据打印不附加文本。
所以看起来接收到的数据不完整。
打印字符串时,不会显示 NewLine 和附加的“done”。
任何帮助都会很棒!
谢谢
class Udp
{
public EventHandler _dataReceived;
public Udp()
{
int receiverPort = 1248;
UdpClient receiver = new UdpClient(receiverPort);
string discovery = "<?xml version=\"1.0\"?><ServiceQuery></ServiceQuery>";
receiver.BeginReceive(new AsyncCallback( DataReceived), receiver);
IPEndPoint end = new IPEndPoint(IPAddress.Broadcast, 1248);
receiver.Send(Encoding.ASCII.GetBytes(discovery + "\0"), discovery.Length + 1, end);
}
private void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 1248);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
string receivedText = ASCIIEncoding.ASCII.GetString(receivedBytes);
Console.WriteLine("\n");
if(_dataReceived != null)
{
Console.Write(receivedIpEndPoint + ": " + receivedText + Environment.NewLine + "done");
_dataReceived(receivedText, new EventArgs());
}
c.BeginReceive(new AsyncCallback(DataReceived), c);
}
}