0

client.ReceiveBufferSize没有给出正确的接收字节大小。

所以我尝试client.Client.SendFile("FileName.png")改用,但仍然给出相同的结果。我还检查了它发送的图像是否超过 64KB,并且确实显示它发送的图像超过了 64KB(从客户端)。

服务器代码:

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);

客户代码:

TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("123.456.789.123"), 12345);
                    byte[] imagebyte = File.ReadAllBytes("ImageCaptured.temp");
                    client.GetStream().Write(imagebyte, 0, imagebyte.Length);
                    File.Delete("ImageCaptured.temp");

假设显示大约 128KB ,client.ReceiveBufferSize但最多只能显示 64KB。

4

1 回答 1

0

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

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

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

客户端代码

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))

于 2019-04-19T01:30:45.430 回答