网络流开始读取/结束读取
我对 C# 编程非常陌生,我正在开发一个基于 TcpClient 的应用程序。
我想知道如何使用 BeginRead & EndRead,我已经阅读了 MSN 文档,但没有帮助。
我有这个:
private void Send() { TcpClient _client = new TcpClient("主机", 80); NetworkStream ns = _client.GetStream(); ns.Flush(); / ... ns.Write(缓冲区, 0, 缓冲区. 长度); int BUFFER_SIZE = 1024; 收到的字节[] = 新字节[BUFFER_SIZE]; ns.BeginRead(收到, 0, 0, new AsyncCallback(OnBeginRead), ns); } 私有无效 OnBeginRead(IAsyncResult ar) { NetworkStream ns = (NetworkStream)ar.AsyncState; int BUFFER_SIZE = 1024; 收到的字节[] = 新字节[BUFFER_SIZE]; 字符串结果 = String.Empty; ns.EndRead(ar); 整型读取; while (ns.DataAvailable) { read = ns.Read(已收到, 0, BUFFER_SIZE); 结果+= Encoding.ASCII.GetString(收到); 收到=新字节[BUFFER_SIZE]; } 结果 = result.Trim(new char[] { '\0' }); // 想要用结果更新这里的表单 }
如何使用结果更新表单组件?
感谢您的帮助。
I'm really new to C# programming and I'm developing an application based on a TcpClient.
I would like to know how to use BeginRead & EndRead, I've already read MSN documentation but doesn't help.
I've this :
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 }
How can I update a Form component using result ?
Thanks for help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我建议学习很多有关多线程的知识。然后回来学习socket。这两个问题都有相当陡峭的学习曲线,并且尝试解决这两个问题需要处理很多。
也就是说,您可以通过
TaskScheduler.FromCurrentSynchronizationContext
捕获 UI 上下文并将Task
调度到该TaskScheduler
,从而向 UI 发布更新。如果 TPL 不可用,那么您可以直接使用SynchronizationContext
。First, I recommend learning a lot about multithreading. Then come back and learn about sockets. Both of these have rather steep learning curves, and trying to tackle both is a lot to handle.
That said, you can post an update to the UI by capturing the UI context via
TaskScheduler.FromCurrentSynchronizationContext
and scheduling aTask
to thatTaskScheduler
. If the TPL isn't available, then you can just useSynchronizationContext
directly.