2

I am trying to write a graphical C# program that can communicate with my Node.js server.

I am using UdpClient class and I am able to send some messages to the server.

However, I don't know how to receive UDP packages from the server. JavaScript and Windows Form Widgets are event-driven, but UdpClient class in C# doesn't have any convenient events related to data reception.

Also, I don't know where to put the code of package reception. Most of online examples are console program and my program is GUI based.

I want my program to continuously listen at a port and when a package comes in, the program can capture the package and display its content in a TextBox.

Any suggestions ?

user3654736
  • 55
  • 1
  • 5

1 Answers1

2

You can listen to a port asynchronously using BeginReceive. It works in GUI applications too - just remember to send the data to the UI thread before interacting with the UI.

This example is from a WinForms application. I've put a multiline textbox on the form called txtLog.

private const int MyPort = 1337;
private UdpClient Client;

public Form1() {
    InitializeComponent();

    // Create the UdpClient and start listening.
    Client = new UdpClient(MyPort);
    Client.BeginReceive(DataReceived, null);
}

private void DataReceived(IAsyncResult ar) {
    IPEndPoint ip = new IPEndPoint(IPAddress.Any, MyPort);
    byte[] data;
    try {
        data = Client.EndReceive(ar, ref ip);

        if (data.Length == 0)
            return; // No more to receive
        Client.BeginReceive(DataReceived, null);
    } catch (ObjectDisposedException) {
        return; // Connection closed
    }

    // Send the data to the UI thread
    this.BeginInvoke((Action<IPEndPoint, string>)DataReceivedUI, ip, Encoding.UTF8.GetString(data));
}

private void DataReceivedUI(IPEndPoint endPoint, string data) {
    txtLog.AppendText("[" + endPoint.ToString() + "] " + data + Environment.NewLine);
}
Anders Carstensen
  • 2,949
  • 23
  • 23