【问题标题】:Testing Broadcasting and receiving messages测试广播和接收消息
【发布时间】:2009-05-15 17:26:59
【问题描述】:

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

【问题讨论】:

    标签: broadcasting


    【解决方案1】:

    udpServer.Receive() 可能是一个阻塞调用,等待数据(它没有得到)

    【讨论】:

    • 但是表格至少不可见吗?
    • @Avik,ryansstack 是对的。您需要启动一个新线程以避免阻塞调用,或者只使用 udpServer.BeginReceive
    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2017-05-31
    相关资源
    最近更新 更多