client.ReceiveBufferSize
doesn't give the right received byte size.
So I have tried to use client.Client.SendFile("FileName.png")
instead and still gives the same result. I have also done a check to make sure that the image that it was sending was more than 64KB and it did show it was sending more than 64KB (From the client side).
Server Code:
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);
Client Code:
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");
The client.ReceiveBufferSize
suppose to show around ~128KB but only shows up to 64KB exactly.
TCP is not a "byte[] in same byte[] out" system. You could have a Write split in to multiple reads or even have multiple writes combined in to a single read.
What you need to do is implement Message Framing in your code. That means you need to send extra data that your receiving side understands to know how much data was sent in a single "message".
Here is a very simple example where the length is sent before the picture then the other side reads the length then reads that number of bytes.
Client code
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);
}
}
Server code
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");
}
Note for the client, if you where not planning on closing the TcpClient and sending more data you would need to replace the using(BinaryWriter writer = new BinaryWriter(client.GetStream()))
with using(BinaryWriter writer = new BinaryWriter(client.GetStream(), Encoding.UTF8, true))