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");
client.ReceiveBufferSize
假设显示大约128KB,但只显示高达64KB。
TCP不是同一字节[] out“系统中的”byte []。您可以将Write拆分为多个读取,甚至可以将多个写入组合到一个读取中。
您需要做的是在代码中实现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))