tags:

views:

28

answers:

1

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  A: 

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

ryansstack
but wont the form atleast be visible?
Avik
@Avik, ryansstack is right. You'll need to start a new thread to avoid the blocking call, or just use udpServer.BeginReceive
Matías