简体   繁体   English

C#异步接收

[英]C# Asynchronous Receive

I've been having some trouble lately while trying to learn how to do an asynchronous receive using visual C#. 我最近在尝试学习如何使用可视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. 它必须每100毫秒左右将数据发送到服务器,然后将其接收回来。

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". 如您所见,它现在所做的只是发送“ 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 编辑:添加客户端对不起我忘了它

Ok, so, what you need to do is when your app is waiting for incoming data, you need to employ the TcpListener class . 好的,因此,您需要做的是当应用程序等待传入数据时,需要使用TcpListener

Try this SO answer 试试这个答案

The TcpListener class listens for incoming connections, and when it finds one, it creates a TcpClient which does its thing. TcpListener类侦听传入的连接,当找到连接时,它将创建一个TcpClient来执行其操作。 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. 我认为(70%肯定)它为新连接创建的TcpClient将在与您的侦听器使用的端口不同的端口上运行。 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. 如果需要,我可以详细说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM