Dusty
Dusty

Reputation: 423

C# Asynchronous Receive

I've been having some trouble lately while trying to learn how to do an asynchronous receive using visual C#. I have a console based server program that receives data from a client and then sends it back. My problem is on the client side. It has to send data to the server every 100 or so milliseconds and then receive it back.

The problem is getting it back because I can't have the program stop and wait for data. Here's what it looks like so far...

IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 16487);
TcpClient client = new TcpClient();

bool blnOnOFF;

private void SendServerData()
{
    string strData = "TEST DATA";

    NetworkStream clientStream = client.GetStream();

    ASCIIEncoding encoder = new ASCIIEncoding();
    byte[] buffer = encoder.GetBytes(strData);

    clientStream.Write(buffer, 0, buffer.Length);
    clientStream.Flush();
}

// Ticks Every 100ms
private void tmrDataTransfer_Tick(object sender, EventArgs e)
{
    SendServerData();
}
private void btnStart(object sender, EventArgs e)
{
    if (blnOnOFF == false)
    {
        tmrDataTransfer.Start();
        blnOnOFF = true;
    }
    else
    {
        tmrDataTransfer.Stop();
        blnOnOFF = false;
    }
}

As you can see, all it does right now is send "TEST DATA". If there is another way to receive the data that is simpler than asynchronous please let me know, also i would like to learn how to do this for future projects.

thanks in advanced.

EDIT: added client sorry i forgot about it

Upvotes: 0

Views: 446

Answers (1)

user47589
user47589

Reputation:

Ok, so, what you need to do is when your app is waiting for incoming data, you need to employ the TcpListener class.

Try this SO answer

The TcpListener class listens for incoming connections, and when it finds one, it creates a TcpClient which does its thing. Meanwhile, the listener has already gone back to looking for new connections. It's pretty much only ever doing just that, and moving the work off to other places.

I think (70% sure) that the TcpClient it creates for a new connection will be operating on a different port than the one your listener is using. You're thus always listening on the same port, while your processing is done on other threads on other ports.

Make sense? I can elaborate more if desired.

Upvotes: 1

Related Questions