将这段代码确保我读了所有我想从一个插座? [英] Will this code make sure I read all I want from a socket?

查看:92
本文介绍了将这段代码确保我读了所有我想从一个插座?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做一个Socket.Receive(字节[])将获得字节从缓冲区,但如果预期的数据是相当大的,所有字节可能尚未在缓冲区中,这会给我一个只有部分填写字节数组。此代码将确保我在所有的读我想要的吗?

Doing a Socket.Receive(byte[]) will get the bytes in from the buffer, but if the expected data is fairly large, all of the bytes might not yet be in the buffer, which would give me an only partially filled byte array. Will this code ensure that I read in all that I want?

sock.Receive(message_byte, message_byte.Length, SocketFlags.None);

其中message_byte已被宣布为我期待中的数据的确切大小。我要对这个以正确的方式?什么是这个手柄会比〜10兆大,因此它不太可能我会宣布字节数组时,一个OutOfMemoryException。

where message_byte has already been declared as the exact size of the data I'm expecting. Am I going about this in the right way? Nothing this handles would be larger than ~10 megs, so it's unlikely I would have an OutOfMemoryException when declaring the byte array.

推荐答案

不,接收返回接收的字节数。你应该妥善处理这一

No, Receive returns number of received bytes. You should properly handle this.

var needBytes = message_byte.Length;
var receivedBytes;
var totalReceivedBytes = 0;
do
{
    receivedBytes = sock.Receive(message_byte, totalReceivedBytes, needBytes, SocketFlags.None);
    needBytes -= receivedBytes;
    totalReceivedBytes += receivedBytes;
} while (needBytes > 0 && receivedBytes > 0)

这篇关于将这段代码确保我读了所有我想从一个插座?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆