C#ReceiveBufferSize显示不正确的值

时间:2019-04-19 00:25:22

标签: c# image tcpclient networkstream

import sys sys.path.insert(0, '/home/ubuntu/pf/basic/transmitter') import encode # or from encode import encoder 没有给出正确的接收字节大小。

因此,我尝试改用import sys sys.path.append('/home/ubuntu/pf/basic/transmitter') import encode # or from encode import encoder ,但仍然给出相同的结果。我还进行了检查,以确保它发送的映像大于64KB,并且确实表明它发送的大于64KB(来自客户端)。

服务器代码:

client.ReceiveBufferSize

客户代码:

client.Client.SendFile("FileName.png")

TcpListener server = new TcpListener(IPAddress.Any,12345); TcpClient client = server.AcceptTcpClient(); NetworkStream clientstream = client.GetStream(); byte[] ImageByte = new byte[client.ReceiveBufferSize]; int ReceiveCount = await clientstream.ReadAsync(ImageByte,0,ImageByte.Length); File.WriteAllBytes("Screenshot.png",ImageByte); 可能会显示约128KB,但最多只能显示64KB。

1 个答案:

答案 0 :(得分:0)

TCP不是“ byte [] in同一byte [] out”系统。您可以将写入拆分为多个读取,甚至可以将多个写入合并为一个读取。

您需要做的是在代码中实现Message Framing。这意味着您需要发送接收方可以理解的额外数据,以了解在单个“消息”中发送了多少数据。

这是一个非常简单的示例,其中在图片之前发送长度,然后另一边读取该长度,然后读取该字节数。

客户代码

using(TcpClient client = new TcpClient())
{
    client.Connect(IPAddress.Parse("123.456.789.123"), 12345);
    using (var clientStream = client.GetStream()) 
    {
        int imageLength = reader.ReadInt32();
        byte[] imagebyte = new byte[imageLength);
        int readBytes = 0;
        while (readBytes < imageLength)
        {
             int nextReadSize = Math.Min(client.Available, imageLength - readBytes);
             readBytes += await clientStream.ReadAsync(imagebyte, readBytes, nextReadSize);
        }
        File.WriteAllBytes("Screenshot.png",imageByte);
    }
}

服务器代码

TcpListener server = new TcpListener(IPAddress.Any,12345);
using(TcpClient client = await server.AcceptTcpClientAsync()) 
{
    byte[] imagebyte = File.ReadAllBytes("ImageCaptured.temp");
    using(BinaryWriter writer = new BinaryWriter(client.GetStream()))
    {
        writer.Write(imagebyte.Length)
        writer.Write(imagebyte, 0, imagebyte.Length);
    }
    File.Delete("ImageCaptured.temp");
}

请注意客户端,如果您不打算关闭TcpClient并发送更多数据,则需要将using(BinaryWriter writer = new BinaryWriter(client.GetStream()))替换为using(BinaryWriter writer = new BinaryWriter(client.GetStream(), Encoding.UTF8, true))