Jon
Jon

Reputation: 21

How to Make Simple C# Windows Form Application UDP Socket Tester

Hello everyone I am very new to Visual Studio, C# programming, and Windows Form Applications.

My need is very simple - I want to create my own small program to listen to data being sent by a GPS device over UDP. I do not need to communicate, just listen and see the data on the screen!

Something that works exactly the same as this :

http://sockettest.sourceforge.net/ (see 'UDP' tab)

My GPS device has an IP of 192.168.1.1 and sends a sting of numbers every 1 second, continuously, transmitting on UDP 25.255.255.255:5017.

All the examples on the internet seems to focus on 2-way communicate, client and server chat windows etc. There is a lot of confusing terminology like synchronous and a-synchronous, client, server, UDP, TCP, binding.

I just want an even more simplified program than the above example, where I can type in the port number 5017, click Start Listening, and then straight away works!

All advice and code examples very gratefully received!!

Many thanks, Jon

Upvotes: 0

Views: 4764

Answers (2)

Akhil
Akhil

Reputation: 1

Run the same code in background worker and then you can cancel the background worker anytime using backgroundworker.cancelasync(). Hope this helps.

Upvotes: 0

Jon
Jon

Reputation: 21

I now have it working, and can receive data in a textbox in the UI!

I use button_start_Click to open the port and start receiving. However, I cannot get button_stop_Click to work. How can you stop/close/disconnect/endReceive using button click?

    public Form1()
    {
        InitializeComponent();
    }

    private void button_start_Click(object sender, EventArgs e)
    {
        Client = new UdpClient(Convert.ToInt32(textBox_port.Text));
        Client.BeginReceive(DataReceived, null);
    }

    private void DataReceived(IAsyncResult ar)
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, Convert.ToInt32(textBox_port.Text));
        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);
    }


    private void button_stop_Click(IAsyncResult ar) // NOT WORKING!! AGH!
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, Convert.ToInt32(textBox_port.Text));
        byte[] data;
        data = Client.EndReceive(ar, ref ip);
        Client.Close();

    }

Upvotes: 1

Related Questions