Event driven TCP Client

Viewed 21393

I want a event-driven, windows, c#, tcp client.

When there are at least 35 bytes in the read buffer, I want a handler to be called that will read those 35 bytes, grab a length value from that "packet", then do a blocking read for that second length of data.

4 Answers

The answer is probably too late. I recently had a similar problem and have developed 2 projects for it. The first one provides an event based TcpClient that has been tested for all major operating systems. It delivers all incoming data as an event that can be easily subscribed to. The 2nd project takes care of the processing of the incoming data. There is an analyzer that waits for a StartToken and then analyzes the length of the package. StartTokenWithLengthInfoDataPackageAnalyzer. You can also implement your own analyzer if the existing one is not sufficient.

var dataPackageAnalyzer = new StartTokenWithLengthInfoDataPackageAnalyzer(0x01);
var dataPackageHandler = new DataPackageHandler(dataPackageAnalyzer);
dataPackageHandler.NewDataPackage += NewDataPackage;

void NewDataPackage(DataPackage dataPackage)
{
    //final package
}

void OnDataReceived(byte[] receivedData)
{
    //fragmented data
    dataPackageHandler.AddData(receivedData);
}

using var cancellationTokenSource = new CancellationTokenSource(1000);
using var tcpClient = new TcpClient();
tcpClient.DataReceived += OnDataReceived;
await tcpClient.ConnectAsync("127.0.0.1", 9000, cancellationTokenSource.Token);

//Wait for data
Console.ReadKey();

tcpClient.Disconnect();
tcpClient.DataReceived -= OnDataReceived;
dataPackageHandler.NewDataPackage -= NewDataPackage;
Related