【问题标题】:TCP ReceiveBufferSize maximum size in .Net Framework.Net Framework 中的 TCP ReceiveBufferSize 最大大小
【发布时间】:2011-12-19 05:00:50
【问题描述】:

我正在尝试使用 System.Net.Sockets 中的 TCP/Sockets 函数来传输文件。 但是,当我尝试在客户端和服务器上动态设置缓冲区的大小时,如果大小小于 4096,则传输做得很好,但如果大于 4096,则缓冲区保持 4096 值,因此文件是没有完全收到。

所以,我想知道?这是最大值吗? 如果是,在客户端使用循环填满并在服务器上使用相同方法接收的 Buffer 是否安全?

感谢您的帮助。

【问题讨论】:

    标签: .net sockets tcp file-transfer


    【解决方案1】:

    我曾经用套接字编写过一个类似且非常简单的文件接收器(只是为了尝试套接字,所以代码不是那么漂亮):

      Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      EndPoint endpoint = new IPEndPoint(IPAddress.Any, 2442);
      socket.Bind(endpoint);
      socket.Listen(10000);
      System.Console.WriteLine("Waiting for incoming data on *:2442");
      Socket client = socket.Accept();
    
      byte[] buffer = new byte[2000];
      List<byte> wholeThing = new List<byte>();
      int count = 0;
      do {
        count = client.Receive(buffer);
        for (int i = 0 ; i < count ; i++)
          wholeThing.Add(buffer[i]);
        System.Console.Write("*");
      } while (count > 0);
      System.Console.WriteLine(Environment.NewLine + "Received {0} bytes of data", wholeThing.Count);
      File.WriteAllBytes(Application.StartupPath + "\\receivedFile", wholeThing.ToArray());
    

    发件人代码如下所示:

        byte[] fileData = File.ReadAllBytes(fileName);
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect(IPAddress.Parse(targetip), 2442);
        int offset = 0;
        do {
          try {
            offset = socket.Send(fileData, offset, fileData.Length - offset, SocketFlags.None);
          } catch {
            socket.Close();
            throw;
          }
        } while (offset < fileData.Length);
    

    【讨论】:

      【解决方案2】:

      如果您尝试发送较大的文件,.net 通常会将它们分成较小的块。您需要在客户端接收到的数据时重新组装数据。我认为 networkComms.net 第 134 行 here 中的 ConnectionPacketBuilder 类可以实现您想要做的事情。您可以看到它是如何使用的,因为数据在第 793 行左右。

      【讨论】:

        猜你喜欢
        • 2021-03-05
        • 1970-01-01
        • 2010-10-27
        • 2010-10-24
        • 2020-05-25
        • 1970-01-01
        • 2011-04-20
        • 1970-01-01
        • 2010-11-25
        相关资源
        最近更新 更多