伙计们在解决这个问题时遇到了一些困难: 我试图测试广播消息和接收消息的代码(在c#中)是否有效:
发送数据报的代码(在本例中是主机名)是:
public partial class Form1 : Form
{
String hostName;
byte[] hostBuffer = new byte[1024];
public Form1()
{
InitializeComponent();
StartNotification();
}
public void StartNotification()
{
IPEndPoint notifyIP = new IPEndPoint(IPAddress.Broadcast, 6000);
hostName = Dns.GetHostName();
hostBuffer = Encoding.ASCII.GetBytes(hostName);
UdpClient newUdpClient = new UdpClient();
newUdpClient.Send(hostBuffer, hostBuffer.Length, notifyIP);
}
}
接收数据报的代码是:
public partial class Form1 : Form
{
byte[] receivedNotification = new byte[1024];
String notificationReceived;
StringBuilder listBox;
UdpClient udpServer;
IPEndPoint remoteEndPoint;
public Form1()
{
InitializeComponent();
udpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 1234));
remoteEndPoint=null;
startUdpListener1();
}
public void startUdpListener1()
{
receivedNotification = udpServer.Receive(ref remoteEndPoint);
notificationReceived = Encoding.ASCII.GetString(receivedNotification);
listBox = new StringBuilder(this.listBox1.Text);
listBox.AppendLine(notificationReceived);
this.listBox1.Items.Add(listBox.ToString());
}
}
为了接收代码我有一个只有一个列表框(listBox1)的表单。 这里的问题是当我执行接收代码时,程序运行但表单不可见。 但是,当我注释函数调用(startUdpListener1())时,目的不是服务但表单是可见的。 怎么回事?
答案 0 :(得分:1)
udpServer.Receive()可能是一个阻塞调用,等待数据(它没有得到)