伙计们很难弄清楚这一点:我正在尝试测试用于广播消息和接收消息的代码(在 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() )时,没有达到目的,但表单是可见的。怎么了?