I have a program with server and client both on different machines. What the program do is send continuous images to server from client. Here client send the datasize first and then the data and similarly server receives the data size in byte[4] and reads the data. Everything is working great but after sometime the datasize byte[] returns some invalid value i.e. -17845811547 or 155488798 and so on. I tried reading the sent and received byte[] and it came to my notice that client is sending the data very well and server is receiving but the server is reading the data sometimes correctly and sometimes it's filling the datasize byte[] with invalid values. Below is the code and invalid result.
Code:
Server -
private static byte[] receiveFullByte(Socket s)
{ int total = 0;
int recv;
byte[] datasize = new byte[4];
recv = s.Receive(datasize, 0, 4, 0);
int size = BitConverter.ToInt32(datasize, 0);
int dataleft = size;
try
{
byte[] data = new byte[size];
while (total < size)
{
if (size > 800000)
{
return null;
}
recv = s.Receive(data, total, dataleft, 0);
if (recv == 0)
{
break;
}
total += recv;
dataleft -= recv;
}
return data;
}
catch (Exception ex)
{
return null;
}
}
Client -
private static void sendDataConti()
{
if (clientSocket.Connected)
{
string request = "Image|" + localipaddress.ipAddressFind() + "||||";
byte[] clientBufferByte = Encoding.ASCII.GetBytes(request);
while (true)
{
//New Code in use below
try
{
using (Bitmap bmp = PrintScreen())
{
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Jpeg);
byte[] buffer = ms.ToArray();
byte[] finalArray = new byte[buffer.Length + clientBufferByte.Length];
Array.Copy(clientBufferByte, 0, finalArray, 0, clientBufferByte.Length);
Array.Copy(buffer, 0, finalArray, clientBufferByte.Length, buffer.Length);
SendFullData(finalArray);
ms.Dispose();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
private static int SendFullData(byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
try
{
//send the size of the data
byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = clientSocket.Send(datasize);
clientSocket.Send(datasize);
Console.WriteLine("Size sent " + size);
logFileWrite(DateTime.Now.ToString("hh:mm:ss.fff") + ": Size sent " + size);
Thread.Sleep(500);
//Console.ReadLine();
//send the image data
while (total < size)
{
sent = clientSocket.Send(data, total, dataleft, SocketFlags.None);
Console.WriteLine("Data sent " + sent);
logFileWrite(DateTime.Now.ToString("hh:mm:ss.fff") + ": Data sent " + sent);
total += sent;
dataleft -= sent;
}
string data2string = Encoding.ASCII.GetString(data);
string request = data2string.Split('|')[0];
logFileWrite(DateTime.Now.ToString("hh:mm:ss.fff") + ": Data2String " + request);
Thread.Sleep(500);
}
catch { }
return total;
}
Result:
Client sent data:
//First data sent
Size sent 126128
Byte 1: 176
Byte 2: 236
Byte 3: 1
Byte 4: 0
Data sent 126128
//Second data sent
Size sent 124521
Byte 1: 105
Byte 2: 230
Byte 3: 1
Byte 4: 0
Data sent 124521
Server received data as:
//First data received which is exactly as sent
Size Received: 126128
Byte 1: 176
Byte 2: 236
Byte 3: 1
Byte 4: 0
//Second data received which is invalid and not same as sent
Size Received: 1734438217
Byte 1: 73
Byte 2: 109
Byte 3: 97
Byte 4: 103
As you can see the first data I have added for you to give an idea that how data is sent and received but during the second data it is not what the client sent. Also do you notice that byte[] values received are invalid. I have no idea what is wrong and from where the server is filling up the byte[] values.
Sandhiya PriyaPosted Jan 7, 2026, 4:30 AM
This is a classic socket framing problem in C#. What’s happening is that your server sometimes reads partial data or extra bytes when trying to interpret the 4-byte length prefix, so the
BitConverter.ToInt32()call ends up producing garbage values.Why It Happens
TCP is a stream protocol: it doesn’t preserve message boundaries. If you send 4 bytes for size and then N bytes for data, the receiver may get:
All 4 size bytes at once
Or 2 size bytes now and 2 later
Or size + part of data together
If you call
socket.Receive(buffer)once, it may not fill the buffer completely. You must loop until all expected bytes are read.Correct Way to Read
You need a helper method that reads exactly N bytes from the socket:
Example: Reading Size + Data
Key Fixes
Always loop until all bytes are read (don’t assume one
Receivecall is enough).Ensure both client and server use the same endianness (
BitConverterdefaults to little-endian).Consider using NetworkStream + BinaryReader/BinaryWriter for cleaner code:
For continuous images, you may want to reuse buffers instead of allocating new ones each time.
If images are large, consider chunked transfer or compression.
Rajesh GamiPosted Jan 3, 2023, 6:29 AM
Check the receive value,