c# – 如何让套接字等待更多数据的到来

c# – 如何让套接字等待更多数据的到来,第1张

概述我正在玩 RserveCLI项目,这是一个与统计环境R通信的.net客户端.基本思想是通过TCP协议在此.NET客户端和R会话之间发送数据/表彰. 其他人和我发现的一个错误就是超大10k字节的大数据中继无法成功传输.我在下面的代码片段中找到了但是: // send the commend to R, then R will do some computation and get the data 我正在玩 RserveCLI项目,这是一个与统计环境R通信的.net客户端.基本思想是通过TCP协议在此.NET客户端和R会话之间发送数据/表彰.

其他人和我发现的一个错误就是超大10k字节的大数据中继无法成功传输.我在下面的代码片段中找到了但是:

// send the commend to R,then R will do some computation and get the data ready to send back        int toConsume = this.submitCommand(cmd,data);         var res = new List<object>();        while (toConsume > 0)        {            var dhbuf = new byte[4];            if (this.socket.Receive(dhbuf) != 4)            {                throw new WebException("DIDn't receive a header.");            }            byte typ = dhbuf[0];            // ReSharper disable RedundantCast            int dlength = dhbuf[1] + (((int)dhbuf[2]) << 8) + (((int)dhbuf[3]) << 16);            // ReSharper restore RedundantCast            var dvbuf = new byte[dlength];            // BUG: I added this sleep line,without this line,BUG occures            System.Threading.Thread.Sleep(500);            // this line cannot receive the whole data at once            var received = this.socket.Receive(dvbuf);            // so the exception throws             if (received != dvbuf.Length)            {                var tempR = this.socket.Receive(dvbuf);                throw new WebException("Expected " + dvbuf.Length + " bytes of data,but received " + received + ".");            }

原因是.NET代码运行得太快而R方无法快速发送数据.因此,插入Thread.Sleep(500)后的接收行无法获取所有数据.如果我在那里等一段时间,那么它可以获得所有数据.但我不知道多久.

我有一些基本的想法来处理这个问题,例如,连续使用this.socket.Receive()来获取数据,但是如果没有数据,那么.Receive会阻塞它.

我在套接字编程方面经验不足,所以我问这种问题的最佳实践.谢谢!

解决方法 根据 docs:

If you are using a connection-orIEnted Socket,the Receive method will read as much data as is available,up to the size of the buffer.

因此,您无需保证在接收电话中获取所有要求的数据.您需要检查Receive实际返回的字节数,然后为剩余字节发出另一个接收调用.继续循环,直到获得所需的所有字节.

总结

以上是内存溢出为你收集整理的c# – 如何让套接字等待更多数据的到来全部内容,希望文章能够帮你解决c# – 如何让套接字等待更多数据的到来所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1234091.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存