11 Replies - 8344 Views - Last Post: 08 July 2012 - 04:24 PM Rate Topic: -----

#1 Brian2sos  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 28-October 09

UDP Async timed sending and receiving on same port

Posted 05 July 2012 - 06:05 PM

Hey Guys,

I recently made the jump from vb to c# and must say that I like it a lot but I am hitting a few speed bumps on the way. Hopefully this will be a straight forward question. I am trying to send a UDP packet on a timed interval (every 100 ms) to some specified port and address. After each send, I am trying to listen/receive on the same port for any response from the last command.

Currently I can send and separately just fine but I can't seem to get it to work at the same time. I am almost positive that I should be using the asynchronous method but I'm just not sure how to implement it. Also, I have been through just about every forum I know and downloaded every example I can find but nothing i have found so far provides examples of sending and receiving on the same port without closing the connection.

I'm not looking for someone to write code for me so just any help on the matter would be great.

Thanks all.

ps. If anyone is interested. I am sending motor control commands to an arduino board. Upon receiving a UDP packet the arduino board sends a response back to the IP address and Port from which the packet was sent from.

This post has been edited by Brian2sos: 05 July 2012 - 06:16 PM


Is This A Good Question/Topic? 0
  • +

Replies To: UDP Async timed sending and receiving on same port

#2 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3649
  • View blog
  • Posts: 11,416
  • Joined: 05-May 12

Re: UDP Async timed sending and receiving on same port

Posted 05 July 2012 - 06:52 PM

Post your current code.
Was This Post Helpful? 0
  • +
  • -

#3 Brian2sos  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 28-October 09

Re: UDP Async timed sending and receiving on same port

Posted 05 July 2012 - 07:53 PM

View PostSkydiver, on 05 July 2012 - 07:52 PM, said:

Post your current code.



I'm clearly missing something since the OnReceive method is never called. By the way. The sending is working great. Also, according to wireshark, a return message is being returned on receipt of a message just as it should.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace UDP_TEST_ASYNC
{
    public partial class Form1 : Form
    {

        public Socket clientSocket;
        public EndPoint epServer;
        byte[] byteData = new byte[1024];


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Using UDP sockets
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //IP address of the server machine
            IPAddress ipAddress = IPAddress.Parse(textBox1.Text);
            //Server is listening on port 8888
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8888);

            epServer = (EndPoint)ipEndPoint;

            byteData = new byte[1024];

            //Start listening to the data asynchronously
            clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string string1 = textBox2.Text;

            byte[] content = Encoding.ASCII.GetBytes(string1);
            //Send it to the server
            clientSocket.BeginSendTo(content, 0, content.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null);

        }

        private void OnSend(IAsyncResult ar)
        {
            try
            {
                clientSocket.EndSend(ar);
            }
            catch (ObjectDisposedException)
            { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void OnReceive(IAsyncResult ar)
        {
        
                clientSocket.EndReceive(ar);

                //Accordingly process the message received

               textBox3.Text = "Just Do Something"; 

                byteData = new byte[1024];

                //Start listening to receive more data from the user
                clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null);

        }


    }
}


This post has been edited by Brian2sos: 05 July 2012 - 08:03 PM

Was This Post Helpful? 0
  • +
  • -

#4 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3649
  • View blog
  • Posts: 11,416
  • Joined: 05-May 12

Re: UDP Async timed sending and receiving on same port

Posted 05 July 2012 - 10:35 PM

Most UDP code I've seen in the past use the UdpClient class.

Something that is jumping out right now is that your OnRecieve() code is calling EndRecieve(). Shouldn't it be calling EndRecieveMessageFrom()?

That is moot, though, since you say that OnRecieve() isn't being called anyway. Are you sure you are not getting any exceptions thrown?

I don't see clientSocket being bound like in: http://msdn.microsof...e/cc163648.aspx
Additionally, although the documentation for BeginRecieveMessageFrom() doesn't say that the socket needs to be bound, the other API BeginRecieveFrom() does state it explicitly.
Was This Post Helpful? 0
  • +
  • -

#5 Brian2sos  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 28-October 09

Re: UDP Async timed sending and receiving on same port

Posted 06 July 2012 - 05:38 AM

View PostSkydiver, on 05 July 2012 - 11:35 PM, said:

Most UDP code I've seen in the past use the UdpClient class.

Something that is jumping out right now is that your OnRecieve() code is calling EndRecieve(). Shouldn't it be calling EndRecieveMessageFrom()?

That is moot, though, since you say that OnRecieve() isn't being called anyway. Are you sure you are not getting any exceptions thrown?

I don't see clientSocket being bound like in: http://msdn.microsof...e/cc163648.aspx
Additionally, although the documentation for BeginRecieveMessageFrom() doesn't say that the socket needs to be bound, the other API BeginRecieveFrom() does state it explicitly.



Thanks for the reply and the article. I'll try binding the socket and see if that makes any difference I sure hope it does.

Thanks
Was This Post Helpful? 0
  • +
  • -

#6 Brian2sos  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 28-October 09

Re: UDP Async timed sending and receiving on same port

Posted 06 July 2012 - 06:13 AM

Binding the endpoint doesn't seem to help anything. Any other suggestions?
Was This Post Helpful? 0
  • +
  • -

#7 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3649
  • View blog
  • Posts: 11,416
  • Joined: 05-May 12

Re: UDP Async timed sending and receiving on same port

Posted 06 July 2012 - 07:57 AM

In the original post, you wrote:

Quote

Currently I can send and separately just fine but I can't seem to get it to work at the same time.


I'm not quite sure how to interpret that. Did you mean to say that you can send and receive separately just fine? e.g. If you run your code as is, you can receive a UDP packet without problems? The problem only occurs when you send a packet, and you don't one back that you were expecting.
Was This Post Helpful? 0
  • +
  • -

#8 Brian2sos  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 28-October 09

Re: UDP Async timed sending and receiving on same port

Posted 06 July 2012 - 11:36 AM

View PostSkydiver, on 06 July 2012 - 08:57 AM, said:

In the original post, you wrote:

Quote

Currently I can send and separately just fine but I can't seem to get it to work at the same time.


I'm not quite sure how to interpret that. Did you mean to say that you can send and receive separately just fine? e.g. If you run your code as is, you can receive a UDP packet without problems? The problem only occurs when you send a packet, and you don't one back that you were expecting.



Sorry, That was poor wording on my part. What I meant is that I can make a separate app to to receive data and it works fine as well as another app to send and it works as well but when I try and combine them I get nothing on the receive. Here is another question. My main goal is to be able to have sockets open with the same IPEndPoint operating at the same time. One for sending data and one for receiving.
Was This Post Helpful? 0
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3649
  • View blog
  • Posts: 11,416
  • Joined: 05-May 12

Re: UDP Async timed sending and receiving on same port

Posted 06 July 2012 - 02:19 PM

Are you on a 64-bit version of Windows? If so: can you move the code in your Form_Load() handler into Form_Shown() handler? WinForms tends to eat exceptions in the Load() event. So, sometimes, things just quietly fail and you have no clue.

For details, see here: http://stackoverflow...pplication-on-a

If you don't want to move the code, there are a couple other options in the StackOverflow answer.

After moving the code, are you getting any exceptions calling BeginRecieveMessageFrom()?
Was This Post Helpful? 0
  • +
  • -

#10 Brian2sos  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 28-October 09

Re: UDP Async timed sending and receiving on same port

Posted 07 July 2012 - 01:33 PM

View PostSkydiver, on 06 July 2012 - 03:19 PM, said:

Are you on a 64-bit version of Windows? If so: can you move the code in your Form_Load() handler into Form_Shown() handler? WinForms tends to eat exceptions in the Load() event. So, sometimes, things just quietly fail and you have no clue.

For details, see here: http://stackoverflow...pplication-on-a

If you don't want to move the code, there are a couple other options in the StackOverflow answer.

After moving the code, are you getting any exceptions calling BeginRecieveMessageFrom()?


I tried moving everything from form load as you suggested and I'm still not seeing any exceptions. is it even possible to listen and send on the same port?
Was This Post Helpful? 0
  • +
  • -

#11 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3649
  • View blog
  • Posts: 11,416
  • Joined: 05-May 12

Re: UDP Async timed sending and receiving on same port

Posted 07 July 2012 - 02:53 PM

If you disable the send code, can you receive on the port?
Was This Post Helpful? 0
  • +
  • -

#12 Brian2sos  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 28-October 09

Re: UDP Async timed sending and receiving on same port

Posted 08 July 2012 - 04:24 PM

Okay, so in the code I have pasted below I am initializing a UDP client on port 11000 and then using it to receive messages on that port. This is working fine as long as I hard code the server side to always send the response message upon receiving a message to port 11000.

What the server needs to do is to respond a send response message to the same address and port that it received the last message.

My problem is that I don't know how to use the same UdpClient Client = new UdpClient(11000); to send a message. I have previously been making an entirely different UDP client for sending messages. Such as

UdpClient ClientSend = new UdpClient(12000); but then the server side would respond to port 12000 and so the udp client I am using to receive would never get the message.

So my main question is how do I use the same udp client to send and receive and can it be done?


using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        
        //Starts a UDP Client using local IP and Port 11000
        UdpClient Client = new UdpClient(11000);


        public Form1()

        {
            InitializeComponent();
        }



        private void Form1_Load(object sender, EventArgs e)
        {

            //Calls the Begin receive using the 
            Client.BeginReceive(new AsyncCallback(recv), null);

        }

        //CallBack
        private void recv(IAsyncResult res)
        {
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 11000);
            byte[] received = Client.EndReceive(res, ref RemoteIpEndPoint);
            Client.BeginReceive(new AsyncCallback(recv), null);
            //Process codes
            MessageBox.Show(Encoding.UTF8.GetString(received));
        
        }

    }
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1