我对C编程很陌生,我正在开发一个基于TCPClient的应用程序。
我想知道如何使用beginread&endread,我已经阅读过msn文档,但没有帮助。
我有这个:

    private void Send()
    {
        TcpClient _client = new TcpClient("host", 80);
        NetworkStream ns = _client.GetStream();
        ns.Flush();
        / ...
        ns.Write(buffer, 0, buffer.Length);

        int BUFFER_SIZE = 1024;
        byte[] received = new byte[BUFFER_SIZE];
        ns.BeginRead(received, 0, 0, new AsyncCallback(OnBeginRead), ns);
    }

    private void OnBeginRead(IAsyncResult ar)
    {
        NetworkStream ns = (NetworkStream)ar.AsyncState;
        int BUFFER_SIZE = 1024;
        byte[] received = new byte[BUFFER_SIZE];
        string result = String.Empty;

        ns.EndRead(ar);

        int read;
        while (ns.DataAvailable)
        {
            read = ns.Read(received, 0, BUFFER_SIZE);
            result += Encoding.ASCII.GetString(received);
            received = new byte[BUFFER_SIZE];
        }
        result = result.Trim(new char[] { '\0' });
        // Want to update Form here with result
    }

如何使用result更新表单组件?
谢谢你的帮助。

最佳答案

首先,我建议您多学习多线程。然后回来学习sockets。两者都有相当陡峭的学习曲线,试图解决两者都是很多要处理的。
也就是说,您可以通过TaskScheduler.FromCurrentSynchronizationContext捕获ui上下文并将Task调度到该TaskScheduler来向ui发布更新。如果tpl不可用,则可以直接使用SynchronizationContext

关于c# - NetworkStream BeginRead/EndRead,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4399917/

10-10 12:41