c# - 通过套接字读取的最大数据

标签 c# sockets networking

我有一个从套接字读取数据的功能。

public int getResp(byte[] Buff, ref int rxBytes)//Buff is byte array of length 150000 bytes
        {          
            while (socet.Available < rxBytes)//rxBytes = 150000
            {
                int socketAvaildata = socet.Available;
                Thread.Sleep(1000);
                if (socketAvaildata == socet.Available)
                    break;
            }
            try
            {
                //Thread.Sleep(100);
                rxBytes = socet.Available;           
                if (rxBytes > 0)
                {
                    socet.Receive(Buff, rxBytes, 0);
                    return rxBytes;
                }
            }
            catch (Exception ex) 
            {

            }
            return -1;
        }

当我们必须读取小数据时,此功能很好用,但是当我们必须读取大数据(超过100000字节)时,它仅返回部分数据。在dubug模式下,我检查了break时控件是否到达socet.Available = 65536
那么,这是我们可以阅读的最大限制,还是我做错了什么?

最佳答案

Receive方法返回实际接收的字节数。因此,只需将该位更改为:

rxBytes = socet.Receive(Buff, rxBytes, 0);
return rxBytes;

请注意,rxBytes可能少于您最初请求的字节数。为确保您已准确读取该字节数,请使用:
public bool TryReadResponse(byte[] buffer, int expectedNumberOfBytes)
{
    try
    {
        int remaining = expectedNumberOfBytes;
        int offset = 0;
        while (remaining > 0)
        {
            int read = socet.Receive(buffer, offset, remaining, SocketFlags.None);
            if (read == 0)
            {
                // other side has closed the connection before sending the requested number of bytes
                return false;
            }

            offset += read;
            remaining -= read;
        }

        return true;
    }
    catch (Exception ex)
    {
        // failure
        return false;
    }
}

我很乐意从参数中删除ref,因为您只对操作是否完全成功感兴趣。

关于c# - 通过套接字读取的最大数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40548744/

相关文章:

java - RabbitMQ 将虚拟机连接到主机

c# - NAudio播放IEEEFloat格式

c++ - 套接字发送错误作为损坏的管道

c# - "distribution of the hash function"是什么意思?

sockets - 通过套接字将 Reducers 中的全局变量/资源更新到 Hadoop 作业跟踪器

windows - 套接字服务器的高效重叠 I/O

c - 处理多个C中的相似代码 "projects"

Delphi - 桥接两个 TCP 端口

c# 自定义表达式变量(因为我没有更好的术语)

c# - 使用设置的最大精度格式化十进制数,但没有不需要的尾随零