简体   繁体   中英

Can I use Asynchronous and Synchronous sockets in one project?

I need to be able to asynchronously receive messages from the server at any time. However, I also want to use Synchronous sockets; when I send a message I want to block until I get a response. Do synchronous and asynchronous play well with each other, or will it cause problems?

In other words, I use BeginReceive() to asynchronously listen. If I call Receive() (synchronous version as I understand), will the next incoming message be picked up by the Receive callback, the BeginReceive callback, both, neither, or worse?

This would be happening in the client, the server can stay 100% asynchronous.

Do synchronous and asynchronous play well with each other?

No. Generally speaking, they don't play well together.

That's not to say that it can never be done, but it's sometimes impossible, and usually confusing and hard to work with. Unless you have a compelling reason to do otherwise, I'd suggest sticking with just one or the other.

From MSDN:

BeginReceive: "Begins to asynchronously receive data from a connected Socket."

So I would say even though BeginReceive is derived from the Socket class it is meant to receive asynchronous data, were as the Receive method is used to retrieve data synchronously from a bound sock.

Yes, it is completely possible, the trick is to hide the asynchronous behaviour in a wrapper which 'appears' to act in a synchronous manner. There is an article on doing exactly that here for the network library NetworkComms.Net.

Disclaimer: I'm a developer for this library.

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