测试广播和接收消息 [英] Testing Broadcasting and receiving messages

查看:120
本文介绍了测试广播和接收消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们在解决这个问题时遇到了一些困难:
我正在尝试测试广播消息和接收消息的代码(在C#中)是否有效:

Guys am having some difficulty figuring this out: I am trying to test whether the code(in c#) to broadcast a message and receiving the message works:

发送数据报的代码(在本例中为主机名)为:

The code to send the datagram(in this case its the hostname) is:

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())时,没有实现该目的,但该窗体是可见的。
出了什么问题?

For the reception of the code I have a form that has only a listbox(listBox1). The problem here is that when i execute the code to receive, the program runs but the form isnt visible. However when I comment the function call( startUdpListener1() ), the purpose isnt served but the form is visible. Whats going wrong?

推荐答案

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

udpServer.Receive() is probably a blocking call, waiting for data (that it isn't getting)

这篇关于测试广播和接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆