简体   繁体   中英

Send and receive through the same socket but in different threads?

I want to send requests on one thread and collect responses on another thread. How would that work, I couldn't match up the request with the response right? Assume that I can't customize the requests/responses. If I send requests on one thread, how would that even work with the receiving thread/end? Wouldn't the stuff it receives be all mixed up because I keep sending stuff to the same socket while it's still receiving the first request?

It sounds like you are writing a multiplexer. If we assume that each request will at some point get exactly one response (assuming no critical error), then you need to keep a queue someone of what requests have been sent, so that as you receive responses you can match responses to requests in the right order. It is essential that you ensure individual requests are written atomically and uninterrupted; this can be done by locking (around the writing), or by creating a separate queue of pending outbound messages.

The way I do this is by using the Task API; each pending response basically maps to a TaskCompletionSource<T> (for some T ); as you receive responses you can TrySetResult (or the error), indicating completion to the caller - who could we using Wait , ContinueWith , or await .

The main open question is if the requests/responses are handled asynchronously by the counterpart or not.
If the server is responding in the same order, than I would add a BlockingCollection as a Fifo queue as store of the data. (The default collection type for BlockingCollection is ConcurrentQueue).
The sender adds to the BlockingCollection and the receiver takes from the collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM