The problem you are facing is likely related to the way you are handling the data reception. Reading data from the stream using 'stream.Read' may not guarantee that you receive all the data at once, you should modify your code to read from the stream in a loop. Personally I will make use of asynchronous methods (await and async) to handle the socket operations, as this will improve your app's efficiency.
You can read up more on the methods and their usage from -
MS Learn | Asynchronous programming[
^]
Your code will look similar to -
private async Task _connect()
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.SendTimeout = 180000;
socket.ReceiveTimeout = 180000;
await socket.ConnectAsync(IPAddress.Parse("10.10.10.120"), 12345);
byte[] myReadBuffer = new byte[1024 * 10];
int numberOfBytesRead = 0;
bool _flag = false;
bool _flagnextreceive = false;
int _recleng = 0;
stream = new NetworkStream(socket);
while (true)
{
if (_flag)
{
numberOfBytesRead = 0;
goto receiveskip;
}
if (numberOfBytesRead == 0)
{
byte[] data = Encoding.ASCII.GetBytes("ACKDUMMY");
await stream.WriteAsync(data, 0, data.Length);
await stream.FlushAsync();
_flag = true;
}
receiveskip:
while (!_flagnextreceive && numberOfBytesRead < myReadBuffer.Length)
{
int bytesRead = await stream.ReadAsync(myReadBuffer, numberOfBytesRead, myReadBuffer.Length - numberOfBytesRead);
if (bytesRead == 0)
{
break;
}
numberOfBytesRead += bytesRead;
if (!_flagnextreceive && numberOfBytesRead >= 4)
{
byte[] _4byteleng = new byte[4];
Buffer.BlockCopy(myReadBuffer, 0, _4byteleng, 0, 4);
Array.Reverse(_4byteleng);
_recleng = BitConverter.ToInt32(_4byteleng, 0);
_flagnextreceive = true;
}
}
if (numberOfBytesRead < _recleng)
{
_flagnextreceive = true;
goto receiveskip;
}
if (numberOfBytesRead == _recleng)
{
_flagnextreceive = false;
goto _next;
}
_next:
if (numberOfBytesRead == 14 && Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead) == "ACCEPTACK")
{
_flag = true;
goto receiveskip;
}
if (numberOfBytesRead == 14 && Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead) == "LINKTEST")
{
byte[] data1 = Encoding.ASCII.GetBytes("ACCEPTLINKTEST");
await stream.WriteAsync(data1, 0, data1.Length);
await stream.FlushAsync();
_flag = true;
goto receiveskip;
}
if (numberOfBytesRead > 14)
{
txt_log.Invoke((Action)(() =>
{
txt_log.AppendText(Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead) + "\r\n");
}));
_flag = true;
goto receiveskip;
}
if (numberOfBytesRead == 0)
{
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Warning: You are disconnected from the host " + ex.Message);
}
}