Testing Broadcasting and receiving messages

允我心安 提交于 2019-12-13 19:18:05

问题


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);


    }
}

And the code to receive the datagram is:

 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());
    }

}

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?


回答1:


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



来源:https://stackoverflow.com/questions/869925/testing-broadcasting-and-receiving-messages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!