How listen to connected and other messages on a Tcp connection using TcpStream ? #4932
Replies: 1 comment 5 replies
-
If you can use Akka.Streams, you may want to take a look at Framing class. It provides convenience methods for handling incoming chunks of bytes and changing them into frames. Documentation shows how to use it to construct client based on var connection = actorSystem.TcpStream()
.OutgoingConnection(endpoint)
.JoinMaterialized(Framing.SimpleFramingProtocol(maximumMessageLength: Int32.MaxValue), Keep.Left);
// 1. handle incoming requests as part of the flow
var handler = connection.SelectAsync(1, async (ByteString request) =>
{
// handle incoming request
return request; // respond to a requester - here with echo message
});
var complete = Source.Single(ByteString.FromBytes(handshake.ToArray()))
.Via(handler)
.To(Sink.Ignore<ByteString>());
complete.Run(materializer); // execute the connection
// 2. handle incoming connection via queues
var (sender, receiver) = Source.Queue<ByteString>(bufferSize: 4, OverflowStrategy.Backpressure)
.Via(connection)
.ToMaterialized(Sink.Queue<ByteString>(), Keep.Both)
.Run(materializer); // execute connection to obtain access queues
await sender.OfferAsync(ByteString.FromBytes(handshake.ToArray()));
var request = await receiver.PullAsync();
while (request.HasValue)
{
// handle new request
await sender.OfferAsync(response); // respond to the caller
request = await receiver.PullAsync(); // take the next request
}
|
Beta Was this translation helpful? Give feedback.
-
My current code does the following -
What I want to achieve - Mechanism to process length pre-fixed binary data.
Initial thought was to use System.IO.Pipelines
I later realised that this can be achieved using Akka.Streams
Beta Was this translation helpful? Give feedback.
All reactions