C# socket receiving incomplete data

I’m working on a server/client pair of apps which work together as a remote file explorer, like Filezilla.
TCP sockets are used for communication, and this is the central class both of them use to handle communication:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public class SocketHelper
{
public static async Task SendAsync(Socket socket, object message)
{
// Size
var sendBuffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
await socket.SendAsync(BitConverter.GetBytes(sendBuffer.Length));
// Payload
var sentBytes = 0;
while (sentBytes < sendBuffer.Length)
{
sentBytes += await socket.SendAsync(sendBuffer);
}
}
public static async Task<string> ReceiveAsync(Socket socket)
{
// Size
var preflightBuffer = new byte[32];
await socket.ReceiveAsync(preflightBuffer);
// Payload
var receiveBuffer = new byte[BitConverter.ToInt32(preflightBuffer)];
var receivedBytes = 0;
while (receivedBytes < receiveBuffer.Length)
{
receivedBytes += await socket.ReceiveAsync(receiveBuffer);
}
return Encoding.UTF8.GetString(receiveBuffer);
}
}
</code>
<code>public class SocketHelper { public static async Task SendAsync(Socket socket, object message) { // Size var sendBuffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)); await socket.SendAsync(BitConverter.GetBytes(sendBuffer.Length)); // Payload var sentBytes = 0; while (sentBytes < sendBuffer.Length) { sentBytes += await socket.SendAsync(sendBuffer); } } public static async Task<string> ReceiveAsync(Socket socket) { // Size var preflightBuffer = new byte[32]; await socket.ReceiveAsync(preflightBuffer); // Payload var receiveBuffer = new byte[BitConverter.ToInt32(preflightBuffer)]; var receivedBytes = 0; while (receivedBytes < receiveBuffer.Length) { receivedBytes += await socket.ReceiveAsync(receiveBuffer); } return Encoding.UTF8.GetString(receiveBuffer); } } </code>
public class SocketHelper
{
    public static async Task SendAsync(Socket socket, object message)
    {
        // Size
        var sendBuffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
        await socket.SendAsync(BitConverter.GetBytes(sendBuffer.Length));

        // Payload
        var sentBytes = 0;

        while (sentBytes < sendBuffer.Length)
        {
            sentBytes += await socket.SendAsync(sendBuffer);
        }
    }

    public static async Task<string> ReceiveAsync(Socket socket)
    {
        // Size
        var preflightBuffer = new byte[32];
        await socket.ReceiveAsync(preflightBuffer);

        // Payload
        var receiveBuffer = new byte[BitConverter.ToInt32(preflightBuffer)];
        var receivedBytes = 0;

        while (receivedBytes < receiveBuffer.Length)
        {
            receivedBytes += await socket.ReceiveAsync(receiveBuffer);
        }

        return Encoding.UTF8.GetString(receiveBuffer);
    }
}

As you can see I’m sending the size first, then counting the amount of bytes sent and received every time in order to coordinate and limit how much I’m sending and receiving.
This works perfectly fine for small ‘messages’, such as simple serialized requests/response objects for directory listings like these:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public class FolderListingRequest
{
public string Path { get; set; }
}
public class FolderListingResponse : Response
{
public IList<FileData> Files { get; set; } = [];
}
</code>
<code>public class FolderListingRequest { public string Path { get; set; } } public class FolderListingResponse : Response { public IList<FileData> Files { get; set; } = []; } </code>
public class FolderListingRequest
{
    public string Path { get; set; }
}

public class FolderListingResponse : Response
{
    public IList<FileData> Files { get; set; } = [];
}

However for larger amounts of data (file download) it falls apart because somewhere during the transfer the messages come in either incomplete or with extra data at the end, making the deserialization fail.
Furthermore, it’s completely inconsistent in when it fails. Sometimes sending 5 files in one go works fine yet sometimes it breaks with one single file.

Here’s the server code which requests and handles file download:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public async Task DownloadFiles(Socket socket, DownloadFilesRequest request)
{
var payload = new Payload
{
Type = PayloadTypeEnum.DownloadFiles,
Data = request,
};
var fileCountToReceive = request.Paths.Count;
var fileCountReceived = 0;
await SocketHelper.SendAsync(socket, payload);
while (fileCountReceived < fileCountToReceive)
{
Console.WriteLine("Receiving file");
var receivedData = await SocketHelper.ReceiveAsync(socket);
var fileData = JsonConvert.DeserializeObject<FileData>(receivedData);
if (fileData == null)
{
Console.WriteLine("Could not deserialize downloaded file info");
}
localFileService.StoreFile(fileData);
fileCountReceived++;
}
}
</code>
<code>public async Task DownloadFiles(Socket socket, DownloadFilesRequest request) { var payload = new Payload { Type = PayloadTypeEnum.DownloadFiles, Data = request, }; var fileCountToReceive = request.Paths.Count; var fileCountReceived = 0; await SocketHelper.SendAsync(socket, payload); while (fileCountReceived < fileCountToReceive) { Console.WriteLine("Receiving file"); var receivedData = await SocketHelper.ReceiveAsync(socket); var fileData = JsonConvert.DeserializeObject<FileData>(receivedData); if (fileData == null) { Console.WriteLine("Could not deserialize downloaded file info"); } localFileService.StoreFile(fileData); fileCountReceived++; } } </code>
public async Task DownloadFiles(Socket socket, DownloadFilesRequest request)
{
    var payload = new Payload
    {
        Type = PayloadTypeEnum.DownloadFiles,
        Data = request,
    };
    var fileCountToReceive = request.Paths.Count;
    var fileCountReceived = 0;
    await SocketHelper.SendAsync(socket, payload);

    while (fileCountReceived < fileCountToReceive)
    {
        Console.WriteLine("Receiving file");
        var receivedData = await SocketHelper.ReceiveAsync(socket);
        var fileData = JsonConvert.DeserializeObject<FileData>(receivedData);

        if (fileData == null)
        {
            Console.WriteLine("Could not deserialize downloaded file info");
        }

        localFileService.StoreFile(fileData);
        fileCountReceived++;
    }
}

And here’s the client’s part which sends the files:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public async Task SendFiles(Socket socket, DownloadFilesRequest request)
{
foreach (var path in request.Paths)
{
var response = new FileData()
{
Path = path,
Contents = localFileService.GetFileContents(path),
};
await SocketHelper.SendAsync(socket, response);
}
}
</code>
<code>public async Task SendFiles(Socket socket, DownloadFilesRequest request) { foreach (var path in request.Paths) { var response = new FileData() { Path = path, Contents = localFileService.GetFileContents(path), }; await SocketHelper.SendAsync(socket, response); } } </code>
public async Task SendFiles(Socket socket, DownloadFilesRequest request)
{
    foreach (var path in request.Paths)
    {
        var response = new FileData()
        {
            Path = path,
            Contents = localFileService.GetFileContents(path),
        };

        await SocketHelper.SendAsync(socket, response);
    }
}

Is it possible that this is some sort of synchronization issue where the client sends more data than the server is designed to receive? Shouldn’t counting the bytes be enough to alleviate this? Should I be using markers for the beginning and ending of the messages instead?
Or am I trying to send too much data at a time? Should I chunk it?

Any thoughts?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật