c# - 异步客户端套接字C#。如何在不阻止程序运行的情况下循环等待来自服务器的信息?

标签 c# winforms sockets asynchronous tcpclient

我创建了与TCP服务器进行通信的类,如下所示:

public class Tcp_client_server_communication
{
    private static TcpClient client;
    private static String response = String.Empty;

    public void Initialize(string ip, int port)
    {
        client = new TcpClient(ip, port);

    }
    public string BeginRead()
    {
        var buffer = new byte[16];
        var ns = client.GetStream();
        ns.BeginRead(buffer, 0, buffer.Length, EndRead, buffer);
     
    }

    public void EndRead(IAsyncResult result)
    {
        var buffer = (byte[])result.AsyncState;
        var ns = client.GetStream();
        var bytesAvalible = ns.EndRead(result);

        MessageBox.Show(Encoding.ASCII.GetString(buffer));
        BeginRead();

    }
}
要调用这些方法,我使用:
.Initialize();
.BeginRead();
它的工作正常,但我想以多行TextBox而不是以MessageBox的形式显示来自服务器的每条消息。
我怎样才能做到这一点?

最佳答案

好了,您可以创建一个List对象来保存所有传递的消息,然后设置一个Timer来经常检查一次是否已将列表添加到其中。在将消息添加到文本框中后,从列表中删除您在每个刻度上阅读的内容。
这个项目要比那时复杂一些,但这是我在中学时期从事的一个老项目:https://github.com/Taloreal/Server-Essentials

关于c# - 异步客户端套接字C#。如何在不阻止程序运行的情况下循环等待来自服务器的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63916590/

相关文章:

c# - DirectoryCatalog 和 AssemblyCatalog 之间的区别

C# Treeview 键全路径

java - ssl 客户端如何接受过期的 SSL 证书

c - C 中的基本套接字编程

c# - 我无法使用 C# 以编程方式设置 IIS 身份验证

c# - WPF 数据绑定(bind)到字符串属性

c# - parking 费计算

c# - 在 C# 中为计时器使用 Graphics.DrawString 时如何减少闪烁?

c# - Winforms DataBinding 是否适用于以编程方式更改的属性?

c++ - 用 C 编写 Linux 服务器的最佳方法(phtreads、select 或 fork?)