Reactive Extensions mix multiple sequences - system.reactive

I'm working in a TCP context and I need to react to incoming data: If too much data is received i need to ignore all but the last received; if no data comes in for a long time I have to send a request to the server.
First proposition is solved like this:
Observable.FromEventPattern<ObjectReceivedEventArgs>( _client, "ObjectReceived" )
.Throttle( TimeSpan.FromMilliseconds( 500 ) )
.Subscribe( args => ... );
Second proposition is solved with a Timer:
Observable.Timer( ... ).Subscribe( ... );
Now, I can mix it this two things so I can send a request to the server if no data comes in, in a timely fashion?

Yes, you can make a second subscription to your source event like this:
Observable.FromEventPattern<ObjectReceivedEventArgs>(_client, "ObjectReceived")
.Select(_ => Unit.Default)
.StartWith(Unit.Default)
.Throttle(TimeSpan.FromSeconds(/*desired timeout here */))
.Take(1).Repeat()
.Subscribe(_ => /* poke server here */);
What this does is start a stream off with a Unit value and attempt to throttle it with the arrival of events. As long as events arrive within the timeout period, the stream is suppressed by the throttle, as soon as events pause for the timespan then OnNext is fired. Note that the Take(1) causes the timeout to keep firing after each subsequent pause even if no further events arrive - simply remove that if you want to only call the server one time after events cease.

Related

Parallel execution: blocking receive, deferred synchronous

I've asked a question about errors that happened while parallel sync and async calls. And answer shed light on an even bigger questions:
Does blocking receive construct replaces .z.ps/.z.pg calls?
If there exists deferred synchronous (used in mserve.q), are there something like deferred asynchronous exists?
My observations based on the previous question. Case 3 from that question is ok:
q)neg[h]({neg[.z.w] x};42); h[]
42
But what if we want to ensure that our message have been sent:
q)neg[h]({neg[.z.w] x};42); neg[h][]; h[]
42
Seems ok, right? If we go further on the documentation we find out that there another type of insurance we have: h"" - message processed on remote, and in this case we've got an error:
q)neg[h]({neg[.z.w] x};42); neg[h][]; h""; h[]
'type
<hangs>
So the proposition is the following - h[] (sent in the appropriate sequence) somehow changes the behaviour of a sender and may be a receiver process to prepare them for such communication.
To answer your first question, I don't think "replace" is correct term, rather the incoming message is expected as it was initiated by the local process, therefore it's not routed towards the .z.ps handler, unlike messages which the process wasn't expecting, where .z.ps can be used to ensure the message isn't unfriendly or whatever the case may be.
When you issue a blocking receive, the O_NONBLOCK flag is cleared and recvfrom() blocks until a message arrives & the O_NONBLOCK flag is replaced
read(0, "h[]\n", 4080) = 4
fcntl(4, F_GETFL) = 0x802 (flags O_RDWR|O_NONBLOCK)
fcntl(4, F_SETFL, O_RDONLY) = 0
recvfrom(4,
"\1\0\0\0\25\0\0\0", 8, 0, NULL, NULL) = 8
recvfrom(4, "\n\0\7\0\0\0unblock", 13, 0, NULL, NULL) = 13
fcntl(4, F_GETFL) = 0x2 (flags O_RDWR)
fcntl(4, F_SETFL, O_RDONLY|O_NONBLOCK) = 0
On your second question, I believe deferred synchronous was introduced in kdb+ v2.3 for the scenario where a client process shouldn't block the remote process while it waits for it's response. Deferred synchronous allows the server to process other client requests, while your client process blocks until the requested info is received. This is fine when the client can't do anything else until it receives the response.
There are cases where neither process should wait for the other - is this what you're referring to? If so then a use case might be something like a tiered gateway system, where one or more gateways send/receive messages to/from each other, but none block or wait. This is done via async callbacks. In a complex system with multiple processes, each request needs to be tagged with an ID while they are inflight so as to track them. Likewise, you would need to track which request came from which connection so as to return results to the correct client.
Here is a simpler example
////////////// PROC A //////////////
q)\p
1234i
q)remoteFunc:{system"sleep 4";neg[.z.w](`clientCallback;x+y)}
////////////// PROC B //////////////
q)h:hopen 1234
q)clientCallback:{0N!x;}; .z.ts:{-1"Processing continues..";}
q)
q)neg[h](`remoteFunc;45;55);system"t 1000"
q)Processing continues..
Processing continues..
Processing continues..
Processing continues..
Processing continues..
100
// process A sent back it's result when it was ready
On your last question
neg[h][] flushes async messages as least as far as tcp/ip. This does not mean the remote has received them.
The chaser h"" flushes any outgoing messages on h, sends it's own request & processes all other messages on h, until it receives it's response.
Chasing async messages is a way to ensure they've been processed on the remote before moving onto the next async message. In your example, the chase followed by a hanging call isn't valid, for one it will error & secondly, it's not a task which requires a guarantee that the previous async message was fully processed before commencing.
Jason

How timeout works in Dispatch

At API there is:
val http = Http.configure(_
.setConnectionTimeoutInMs(1)
)
What for is this config? I use it with:
.setMaxRequestRetry(0)
I fought I will get failed future after timeout. Future I create like that:
val f = http(u OK as.String)
f.map {
NotificationClientConnectionParams.parseFromString
}
But instead of failure I get success long after my timeout.
How it should work?
My test looks like this:
val startTime = java.time.LocalTime.now()
val f = TcpUtil2.registerClientViaDispatch(ClientHeaders("12345", "123456789"))
f onSuccess {
case c =>
println(s"Success: $c")
println(java.time.Duration.between(startTime, java.time.LocalTime.now()).toMillis)
}
f onFailure {
case e =>
println(s"failure:${e.getMessage}")
}
Thread.sleep(2000)
Response time is in hundreds of milliseconds and I got success. Is it a bug of dispatch?
An HTTP roundtrip goes through several phases (overly simplified):
establishing connection
connection established
sending request payload
request payload sent
waiting for response payload
receiving response payload
response payload received
From what I understand you measure the time between states 1 and 7.
setConnectionTimeoutInMs comes from async-http-client which is used by Dispatch internally. Here's an excerpt from its documentation:
Set the maximum time in millisecond an AsyncHttpClient can wait when connecting to a remote host
Thus, this method sets the maximum time the client will wait between states 1 and 2.
There's also setRequestTimeoutInMs:
Set the maximum time in millisecond an AsyncHttpClient wait for a response
This method seems to set the time between states 5 and 6 (or 7, I'm not sure which one).
So here's what's probably happening in your case. You connect to remote host, the server accepts the connection very quickly (the time between 1 and 2 is small), so your Future doesn't get failed. Then there are several options: either server takes a lot of time to prepare the response before it starts sending it back to you (the time between 5 and 6), or the response is very big so it takes a lot of time to deliver it to you (the time between 6 and 7), or both. But since you don't set the request timeout, your Future is not getting failed because of this.

Akka actor remote dissociation from sending a delayed response

So I have a client server based program, where the client will send a request to the server, the server will do a computation and response. This is done via ask.
Specifically the client will receive a message from the client app and send call ask
val response = ask(actorRef, SessionMessage(token, message)).mapTo[ResponseMessage]
The server will receive it like so
val response = sessionMessage.message match {
case message: message1 =>
ask(actorSet.actor1,message)
case message: message2 =>
ask(actorSet.actor2,message)
Where the actorset is literally a set of the different actors.
I then collect the result and send back to the sender
val responseResult = response.mapTo[ResponseMessage]
responseResult pipeTo sender
The problem I'm running into is that for some of the requests, the database query can take a while (5-10 minutes) and when the query completes it sends to dead letters and I get a dissociation and it is unable to associate again and sends to dead letters.
I thought that because it took so long, that the sender would time out (or specifically the sender reference) so I stored the sender reference as a val, and confirmed that by doing this I the sender reference was lost. However, as soon as as the query finishes and I pipe it to the correct sender, it dissociates. Even other queries that take a minute or so don't seem to suffer this problem, only ones that last for a few minutes dissociate and I need to restart the server or the server will keep sending to dead letters.
Even if I do a onComplete then send on success or do an Await.result, the same issue occurs, as soon as it tries to send the message (after completion) the server dissociates and sends to dead letters.
I'm very much at lost as to why this is happening.
The problem you are into is that ask itself has a timeout, which is separate from a timeout you might specify in Await.result. The full signature to ask is:
def ask (actorRef: ActorRef, message: Any)(implicit timeout: Timeout): Future[Any]
This means that if you did not manually provide a value for timeout and did not define an implicit yourself, you must be inheriting one via one of your imports.
To extend the timeout for your particular ask, simply call it with one:
ask(actorRef, SessionMessage(token, message))(15.minutes).mapTo[ResponseMessage]
or if this applies to all asks in scope, declare your own implicit:
implicit val timeout = Timeout(15.minutes)

Streaming data in and out simultaneously on a single HTTP connection in play

streaming data out of play, is quite easy.
here's a quick example of how I intend to do it (please let me know if i'm doing it wrong):
def getRandomStream = Action { implicit req =>
import scala.util.Random
import scala.concurrent.{blocking, ExecutionContext}
import ExecutionContext.Implicits.global
def getSomeRandomFutures: List[Future[String]] = {
for {
i <- (1 to 10).toList
r = Random.nextInt(30000)
} yield Future {
blocking {
Thread.sleep(r)
}
s"after $r ms. index: $i.\n"
}
}
val enumerator = Concurrent.unicast[Array[Byte]] {
(channel: Concurrent.Channel[Array[Byte]]) => {
getSomeRandomFutures.foreach {
_.onComplete {
case Success(x: String) => channel.push(x.getBytes("utf-8"))
case Failure(t) => channel.push(t.getMessage)
}
}
//following future will close the connection
Future {
blocking {
Thread.sleep(30000)
}
}.onComplete {
case Success(_) => channel.eofAndEnd()
case Failure(t) => channel.end(t)
}
}
}
new Status(200).chunked(enumerator).as("text/plain;charset=UTF-8")
}
now, if you get served by this action, you'll get something like:
after 1757 ms. index: 10.
after 3772 ms. index: 3.
after 4282 ms. index: 6.
after 4788 ms. index: 8.
after 10842 ms. index: 7.
after 12225 ms. index: 4.
after 14085 ms. index: 9.
after 17110 ms. index: 1.
after 21213 ms. index: 2.
after 21516 ms. index: 5.
where every line is received after the random time has passed.
now, imagine I want to preserve this simple example when streaming data from the server to the client, but I also want to support full streaming of data from the client to the server.
So, lets say i'm implementing a new BodyParser that parses the input into a List[Future[String]]. this means, that now, my Action could look like something like this:
def getParsedStream = Action(myBodyParser) { implicit req =>
val xs: List[Future[String]] = req.body
val enumerator = Concurrent.unicast[Array[Byte]] {
(channel: Concurrent.Channel[Array[Byte]]) => {
xs.foreach {
_.onComplete {
case Success(x: String) => channel.push(x.getBytes("utf-8"))
case Failure(t) => channel.push(t.getMessage)
}
}
//again, following future will close the connection
Future.sequence(xs).onComplete {
case Success(_) => channel.eofAndEnd()
case Failure(t) => channel.end(t)
}
}
}
new Status(200).chunked(enumerator).as("text/plain;charset=UTF-8")
}
but this is still not what I wanted to achieve. in this case, I’ll get the body from the request only after the request was finished, and all the data was uploaded to the server. but I want to start serving request as I go. a simple demonstration, would be to echo any received line back to the user, while keeping the connection alive.
so here's my current thoughts:
what if my BodyParser would return an Enumerator[String] instead of List[Future[String]]?
in this case, I could simply do the following:
def getParsedStream = Action(myBodyParser) { implicit req =>
new Status(200).chunked(req.body).as("text/plain;charset=UTF-8")
}
so now, i'm facing the problem of how to implement such a BodyParser.
being more precise as to what exactly I need, well:
I need to receive chunks of data to parse as a string, where every string ends in a newline \n (may contain multiple lines though...). every "chunk of lines" would be processed by some (irrelevant to this question) computation, which would yield a String, or better, a Future[String], since this computation may take some time. the resulted strings of this computation, should be sent to the user as they are ready, much like the random example above. and this should happen simultaneously while more data is being sent.
I have looked into several resources trying to achieve it, but was unsuccessful so far.
e.g. scalaQuery play iteratees -> it seems like this guy is doing something similar to what I want to do, but I couldn't translate it into a usable example. (and the differences from play2.0 to play2.2 API doesn't help...)
So, to sum it up: Is this the right approach (considering I don't want to use WebSockets)? and if so, how do I implement such a BodyParser?
EDIT:
I have just stumble upon a note on the play documentation regarding this issue, saying:
Note: It is also possible to achieve the same kind of live
communication the other way around by using an infinite HTTP request
handled by a custom BodyParser that receives chunks of input data, but
that is far more complicated.
so, i'm not giving up, now that I know for sure this is achievable.
What you want to do isn't quite possible in Play.
The problem is that Play can't start sending a response until it has completely received the request. So you can either receive the request in its entirety and then send a response, as you have been doing, or you can process requests as you receive them (in a custom BodyParser), but you still can't reply until you've received the request in its entirety (which is what the note in the documentation was alluding to - although you can send a response in a different connection).
To see why, note that an Action is fundamentally a (RequestHeader) => Iteratee[Array[Byte], SimpleResult]. At any time, an Iteratee is in one of three states - Done, Cont, or Error. It can only accept more data if it's in the Cont state, but it can only return a value when it's in the Done state. Since that return value is a SimpleResult (i.e, our response), this means there's a hard cut off from receiving data to sending data.
According to this answer, the HTTP standard does allow a response before the request is complete, but most browsers don't honor the spec, and in any case Play doesn't support it, as explained above.
The simplest way to implement full-duplex communication in Play is with WebSockets, but we've ruled that out. If server resource usage is the main reason for the change, you could try parsing your data with play.api.mvc.BodyParsers.parse.temporaryFile, which will save the data to a temporary file, or play.api.mvc.BodyParsers.parse.rawBuffer, which will overflow to a temporary file if the request is too large.
Otherwise, I can't see a sane way to do this using Play, so you may want to look at using another web server.
"Streaming data in and out simultaneously on a single HTTP connection in play"
I haven't finished reading all of your question, nor the code, but what you're asking to do isn't available in HTTP. That has nothing to do with Play.
When you make a web request, you open a socket to a web server and send "GET /file.html HTTP/1.1\n[optional headers]\n[more headers]\n\n"
You get a response after (and only after) you have completed your request (optionally including a request body as part of the request). When and only when the request and response are finished, in HTTP 1.1 (but not 1.0) you can make a new request on the same socket (in http 1.0 you open a new socket).
It's possible for the response to "hang" ... this is how web chats work. The server just sits there, hanging onto the open socket, not sending a response until someone sends you a message. The persistent connection to the web server eventually provides a response when/if you receive a chat message.
Similarly, the request can "hang." You can start to send your request data to the server, wait a bit, and then complete the request when you receive additional user input. This mechanism provides better performance than continually creating new http requests on each user input. A server can interpret this stream of data as a stream of distinct inputs, even though that wasn't necessarily the initial intention of the HTTP spec.
HTTP does not support a mechanism to receive part of a request, then send part of a response, then receive more of a request. It's just not in the spec. Once you've begun to receive a response, the only way to send additional information to the server is to use another HTTP request. You can use one that's already open in parallel, or you can open a new one, or you can complete the first request/response and issue an additional request on the same socket (in 1.1).
If you must have asynchronous io on a single socket connection, you might want to consider a different protocol other than HTTP.

How does zmq poller work?

I am confused as to what poller actually does in zmq. The zguide goes into it minimally, and only describes it as a way to read from multiple sockets. This is not a satisfying answer for me because it does not explain how to have timeout sockets. I know zeromq: how to prevent infinite wait? explains for push/pull, but not req/rep patterns, which is what I want to know how to use.
What I am attempting to ask is: How does poller work, and how does its function apply to keeping track of sockets and their requests?
When you need to listen on different sockets in the same thread, use a poller:
ZMQ.Socket subscriber = ctx.socket(ZMQ.SUB)
ZMQ.Socket puller = ctx.socket(ZMQ.PULL)
Register sockets with poller (POLLIN listens for incoming messages)
ZMQ.Poller poller = ZMQ.Poller(2)
poller.register(subscriber, ZMQ.Poller.POLLIN)
poller.register(puller, ZMQ.Poller.POLLIN)
When polling, use a loop:
while( notInterrupted()){
poller.poll()
//subscriber registered at index '0'
if( poller.pollin(0))
subscriber.recv(ZMQ.DONTWAIT)
//puller registered at index '1'
if( poller.pollin(1))
puller.recv( ZMQ.DONTWAIT)
}
Choose how you want to poll...
poller.poll() blocks until there's data on either socket.
poller.poll(1000) blocks for 1s, then times out.
The poller notifies when there's data (messages) available on the sockets; it's your job to read it.
When reading, do it without blocking: socket.recv( ZMQ.DONTWAIT). Even though poller.pollin(0) checks if there's data to be read, you want to avoid any blocking calls inside the polling loop, otherwise, you could end up blocking the poller due to 'stuck' socket.
So, if two separate messages are sent to subscriber, you have to invoke subscriber.recv() twice in order to clear the poller, otherwise, if you call subscriber.recv() once, the poller will keep telling you there's another message to be read. So, in essence, the poller tracks the availability and number of messages, not the actual messages.
You should run through the polling examples and play with the code, it's the best way to learn.
Does that answer your question?
In this answer i listed
Details from the documentation http://api.zeromq.org/4-1:zmq-poll
Also i added some important explanation and things that clear confusion for new commers! If you are in a hurry! You may like to start by What the poller do and What about Recieving and A note about recieving and what about one socket only sections at the end! Starting from important notes section! Where i clear things in depth! I still suggest reading well the details in the doc ref! And first section!
Doc ref and notes
Listen to multiple sockets and events
The zmq_poll() function provides a mechanism for applications to multiplex input/output events in a level-triggered fashion over a set of sockets. Each member of the array pointed to by the items argument is a zmq_pollitem_t structure. The nitems argument specifies the number of items in the items array. The zmq_pollitem_t structure is defined as follows:
typedef struct
{
void //*socket//;
int //fd//;
short //events//;
short //revents//;
} zmq_pollitem_t;
zmq Socket or standard socket through fd
For each zmq_pollitem_t item, zmq_poll() shall examine either the ØMQ socket referenced by socket or the standard socket specified by the file descriptor fd, for the event(s) specified in events. If both socket and fd are set in a single zmq_pollitem_t, the ØMQ socket referenced by socket shall take precedence and the value of fd shall be ignored.
Big note (same context):
All ØMQ sockets passed to the zmq_poll() function must share the same ØMQ context and must belong to the thread calling zmq_poll().
Revents member
For each zmq_pollitem_t item, zmq_poll() shall first clear the revents member, and then indicate any requested events that have occurred by setting the bit corresponding to the event condition in the revents member.
Upon successful completion, the zmq_poll() function shall return the number of zmq_pollitem_t structures with events signaled in revents or 0 if no events have been signaled.
Awaiting for events and blocking
If none of the requested events have occurred on any zmq_pollitem_t item, zmq_poll() shall wait timeout microseconds for an event to occur on any of the requested items. If the value of timeout is 0, zmq_poll() shall return immediately. If the value of timeout is -1, zmq_poll() shall block indefinitely until a requested event has occurred on at least one zmq_pollitem_t. The resolution of timeout is 1 millisecond.
0 => doesn't wait
-1 => block
+val => block and wait for the timeout amount
Events
The events and revents members of zmq_pollitem_t are bit masks constructed by OR'ing a combination of the following event flags:
ZMQ_POLLIN
For ØMQ sockets, at least one message may be received from the socket without blocking. For standard sockets this is equivalent to the POLLIN flag of the poll() system call and generally means that at least one byte of data may be read from fd without blocking.
ZMQ_POLLOUT
For ØMQ sockets, at least one message may be sent to the socket without blocking. For standard sockets this is equivalent to the POLLOUT flag of the poll() system call and generally means that at least one byte of data may be written to fd without blocking.
ZMQ_POLLERR
For standard sockets, this flag is passed through zmq_poll() to the underlying poll() system call and generally means that some sort of error condition is present on the socket specified by fd. For ØMQ sockets this flag has no effect if set in events, and shall never be returned in revents by zmq_poll().
Note:
The zmq_poll() function may be implemented or emulated using operating system interfaces other than poll(), and as such may be subject to the limits of those interfaces in ways not defined in this documentation.
Return value
Upon successful completion, the zmq_poll() function shall return the number of zmq_pollitem_t structures with events signaled in revents or 0 if no events have been signaled. Upon failure, zmq_poll() shall return -1 and set errno to one of the values defined below.
Example
Polling indefinitely for input events on both a 0mq socket and a standard socket.
zmq_pollitem_t items [2];
/* First item refers to ØMQ socket 'socket' */
items[0].socket = socket;
items[0].events = ZMQ_POLLIN;
/* Second item refers to standard socket 'fd' */
items[1].socket = NULL;
items[1].fd = fd;
items[1].events = ZMQ_POLLIN;
/* Poll for events indefinitely */
int rc = zmq_poll (items, 2, -1);
assert (rc >= 0); /* Returned events will be stored in items[].revents */
Important notes
What the poller do and What about Recieving
The poller only check and await for when events occure!
POLLIN is for receiving! Data is there for recieving!
Then we should read through recv()! We are responsible to read or do anything! The poller is just there to listen to the events and await for them! And through zmq_pollitem_t we can listen to multiple events! If any event happen! Then the poller unblock! We can check then the event in the recv! and zmq_pollitem_t! Note that the poller queue the events as they trigger! And next call will pick from the queue! The order because of that is also kept! And successive calls will return the next event and so on! As they came in!
A note about recieving and what about one socket only
For a Router! A one router can receive multiple requests even from a one client! And also from multiple clients at once! In a setup where multiple clients are of same nature! And are the ones connecting to the router! A question that can cross the mind of a new commer is! Do i need a poller for this async nature! The anwser is no! No need for a poller and listening for different sockets!
The big note is: Receiving calls (zmq_recv(), socket.recv() some lang binding)! Block! And are the way to read! When messages come! They are queued! The poller have nothing to do with this! The poller only listen to events from different sockets! And unblock if any of them happen! if the timeout is reached then no event happen! And does no more then that!
The nature of receiving is straight forward! The recieve call blocks! Till a message in the message queue comes! When multiple come they will get queued! Then on each next call for recv()! We will pull the next message! Or frame! (Depending on what recieving method we are using! And the api level! And abstraction from the binding library to the low level one!)
Because we can access too the messages by frame! a frame at each call!
But then here it becomes clear!
Recieve calls are the things to recieve! They block till a message enter the queue! Multiple parallel messages! Will enter the queue as they come! Then for each call! Either the queue is filled or not! consume it! or wait!
That's a very important thing to know! And which can confuse new commers!
The poller is only needed when there is multiple sockets! And they are always sockets that we declare on the process code in question (bind them, or to connect to something)! Because if not! How will you recieve the messages! You can't do it well! because you have to prioritize one or another! in a loop having one recv() go first ! Which will block! Which even if the other socket get a message in it's queue! The loop is blocked and can't proceed to the next recv()! hince the poller give us the beauty to be able to tackle this! And work well with multiple sockets!
while(true) {
socket1.recv() // this will block
socket2.recv() // this will have to wait till the first recieve! Even if messages come in in it's queue
With the poller:
While(true) {
zmq_poll() // block till one of the socket events happen! If the event was POLLIN!
// If any socket get a message to it's queue
// This will unblock
// then we check which type and which socket was
if (condition socket 1) {
// treat socket 1 request
}
if (condition socket 2) {
// treat socket 2 request
}
// ...
}
You can see real code from the doc at this section (scroll enough to see the code blocks, you can see in all different langs too)
Know that the poller just notify that there is messages in! If it's POLLIN!
In each iteration! The poller if many events triggered already! Let's give the example of 10 messages recieved 5 in each socket! Here the poller already have the events queued! And in each next call for the 9 times! Will resolve immediately! The message in question can be mapped to what socket (by using the poller object and mean! So binding libraries make it too simple and agreable)! Then the right socket block will make the recieve call! And when it does it will consume it's next message from it's queue!
And so you keep looping and each time consuming the next message! As they came in! And the poller tracked there order of comming in! And that through the subscription and the events that were choosen to listen to! In case of receiving, it should be POLLIN!
Then each socket have it's message queue! And each recieve call! Pull from it! The poller tracked them! And so when the poller resolve! It's assured that there is message for the sockets recieve calls!
Last example: The server client pattern
Let's take the example of one server (router) and many clients (Dealers) that connect to! As by the image bellow!
Question: many connections to the same router! Comming asynchronously at once! And bla bla bla! In the server side (Router)! Do i need a poller !? A lot of new commers, may think yes or question if it's needed! Yup you guess right!
BIG NO!
Why ? Because in the Server (router) code! We have only one socket we are dealing with! That we bind! The clients then are connecting to it! In that end! There is only one socket! And all recv() calls are on that one socket! And that socket have it's message queue! The recv() consume the message one after another! Doesn't matter asynchronous and how they comes! Again the poller is only when there is multiple sockets! And so having the mixing nature of treating messages comming from multiple sockets! If not! Then one recv() of one socket need to go first then the other! And will block the other! Not a good thing (it's bad)!
Note
This answer bring a nice clearing! Plus it mades a reference to the doc with good highlighting! Also show code by the low level lib (c lang)! The answer of #rafflan show a great code with a binding lib (seems c#)! And a great explanation! If you didn't check it you must!