Event Driven TCP Client

Please understand me in the right direction.

I need an event driven client, windows, C #, tcp.

When there are at least 35 bytes in the read buffer, I want the calling handler to read these 35 bytes, grab the length value from this β€œpacket”, and then execute the lock read for this second data length.

I can easily do this with sockets, without events ......., but now it is the β€œ20th” :-) century, and I need to enter an event-driven world.

Your help is appreciated.

Chuck

+6
source share
3 answers

There is a relatively new project that essentially provides this: https://github.com/clariuslabs/reactivesockets

On the page:

Implements a very easy to use socket API based on IObservable. It allows very simple protocol implementations, such as:

var client = new ReactiveClient("127.0.0.1", 1055); // The parsing of messages is done in a simple Rx query over the receiver observable // Note this protocol has a fixed header part containing the payload message length // And the message payload itself. Bytes are consumed from the client.Receiver // automatically so its behavior is intuitive. IObservable<string> messages = from header in client.Receiver.Buffer(4) let length = BitConverter.ToInt32(header.ToArray(), 0) let body = client.Receiver.Take(length) select Encoding.UTF8.GetString(body.ToEnumerable().ToArray()); // Finally, we subscribe on a background thread to process messages when they are available messages.SubscribeOn(TaskPoolScheduler.Default).Subscribe(message => Console.WriteLine(message)); client.ConnectAsync().Wait(); 
+4
source

To move in the right direction, look at Socket.BeginReceive() and Socket.BeginSend() .

In addition, it is a convenient series of examples from Microsoft for using the above functions. It helped me start with them.

Unfortunately, I do not see the possibility of calling a callback if there should be at least 35 bytes in the read buffer; it will be called when something is received, even if it is zero. However, most likely, the counterparty will not send you message bytes by bytes in any case.

+1
source

I don't believe that BCL has an event-based socket class, but if you're just looking for something higher than the bare Socket , you might want to look into TcpClient . It will handle base stream buffering for you, allowing you to access it through StreamReader and the like:

 TcpClient client; // ... construct, connect, etc ... new StreamReader(client.GetStream()); 

If you use a string-based protocol, you will need to use StreamReader.ReadLine() , but StreamReader.Read() should easily fit your goals.

+1
source

Source: https://habr.com/ru/post/921813/


All Articles