Here I am again to show you a little bit of asynchronous communication in C#. A few months ago I ended up developing an application and learning more about asynchronous stuff. It’s pretty easy, MSDN documentation is pretty clear so I’ll try to be focus here…
If you’d like to read before getting started, check this out.
All right, so what exactly am I going to do here? I’m thinking of develop an application that sends a message using UDP protocol to another machine (both bound to an IP and some random port), the other machine will be listening to its port (this is the asynchronous part), get the message and show it to us. Pretty simple, huh?
So, let’s get started with our code. I just created an application, dragged and dropped some components, it looks like this now:
Our application will run as the sender and the receiver at the same time, to make it more beautiful, you can open 2 instances of the same app, bind each one to different ports and send the message to each other, it will probably run in different machines too, since they are in the same network. Alegre
So, before our application starts to send message to the other app, we must configure all the network stuff.
Since I’m running these apps in the same machine, both will have the same IP, here I have a simple way to get your own ip:
Then this is my Form_Load method:
Going to our button START onto its click method, here is what I have:
Simply I have created two EndPoints, one for local and another for remote, so I’m binding my socket to local information and connecting it to remote information, in this case, I am able to send and receive information from this Socket. And last, I called a method called (lol) BeginReceiveFrom which represents an asynchronous method. In a few words, this method gets a thread and keeps it running until something happen, once it does, it calls a delegate I called OperatorCallBack, which is an AsyncCallback delegate.
Almost done now, before we forget, we are not sendint any information yet, so go to you SEND button and it should look like this:
I believe the first time you run your application if you have your firewall enabled, Windows will ask if you allow your app to use its resources like this: