如何在异步方法中使用AcceptTcpClient

发布于 2024-10-31 03:44:57 字数 1044 浏览 0 评论 0原文

我正在使用 C++/CLI 编写一个使用 TcpListener 的小程序,我知道 AcceptTcpClient 是一个同步方法,它会阻塞 UI 线程。我怎样才能调用这个方法,这样它就不会阻塞我的用户界面?这是我的代码:

TcpClient^ client = server->AcceptTcpClient();
sendConsoleResult( "Connected to Client, waiting for for instructions..." );
data = nullptr;
// Get a stream Object* for reading and writing
NetworkStream^ stream = client->GetStream();
Int32 i;
// Loop to receive all the data sent by the client.
while ( i = stream->Read( bytes, 0, bytes->Length ))
{
    // Translate data bytes to a ASCII String*.
    data = Encoding::ASCII->GetString( bytes, 0, i );
    sendConsoleResult("[RECEIVED]: "+ data);
    // Process the data then send to command processing module
    data = data->ToUpper();
    response = commandProcess(data)->ToUpper();
    array<Byte>^msg = Encoding::ASCII->GetBytes( response );
    // Send back a response.
    stream->Write( msg, 0, msg->Length );
    sendConsoleResult("[RESPONSE]: " + response);
}

感谢您回答我的问题:

I am making a small program using C++/CLI that use TcpListener, I know that AcceptTcpClient is a synchronous method, which blocking UI thread. How can I call this method so that it won't block my UI? Here is my code:

TcpClient^ client = server->AcceptTcpClient();
sendConsoleResult( "Connected to Client, waiting for for instructions..." );
data = nullptr;
// Get a stream Object* for reading and writing
NetworkStream^ stream = client->GetStream();
Int32 i;
// Loop to receive all the data sent by the client.
while ( i = stream->Read( bytes, 0, bytes->Length ))
{
    // Translate data bytes to a ASCII String*.
    data = Encoding::ASCII->GetString( bytes, 0, i );
    sendConsoleResult("[RECEIVED]: "+ data);
    // Process the data then send to command processing module
    data = data->ToUpper();
    response = commandProcess(data)->ToUpper();
    array<Byte>^msg = Encoding::ASCII->GetBytes( response );
    // Send back a response.
    stream->Write( msg, 0, msg->Length );
    sendConsoleResult("[RESPONSE]: " + response);
}

Thank you for answering my question:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赏烟花じ飞满天 2024-11-07 03:44:57

切换到使用 TcpListener.BeginAcceptTcpClient,以及使用 NetworkStream.BeginRead 。这将使您的整个操作异步,并且不会阻塞您的用户界面线程。

Switch to using TcpListener.BeginAcceptTcpClient, as well as using NetworkStream.BeginRead. This will make your entire operation asynchronous, and not block your user interface thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文