views:

128

answers:

1

I am writing a client program that uses Sockets. I would like the client to receive asyncronously UNLESS it is expecting a response, in which case I would like to receive syncronously.

My current problem is that because I have to make a call to socket.BeginReceive which waits until there's data on the buffer, the async call always happens prior to the sync call..

How could I temporarily stop BeginReceive from executing? Is there a way to call EndReceive and then once I am done receiving syncronously, I can continue to receive asnycronously?

A: 

As far as I know there is no way to stop a BeginReceive short from shutting down the Socket. To do what you're trying to accomplish, you would need to move your calls to using completely synchronous, and put the calls you want to make asynchronously into separate threads. You'd then kill/pause the thread when you want to make an additional call. You could also set the ReceiveTimeout property to something low and have it continue looping until it sees a request to stop, like setting a class wide variable.

Simply for curiosity's sake, why do you want to make a synchronous call if you're already receiving asynchronously?

nasufara
The reason why I would like to have both sync and async is because my client receives 2 types of messages: 1-it asks the server something and expects and answer which is easier to accomplish via sync reception, 2-the server sends an unexpected but important message, in which case it makes most sense to use async reception.Now, if there is no way to combine the two styles, I wil have to accomplish step 1 in async..My only problem is sometimes I have the need to send multiple commands and expect answers, and the server may not respond fast enough, resulting in replies being mixed up
sbenderli
Even if you except a response synchronously, it may still take some time for the reply to be fully received, even if it's on a local network. I also think you misunderstand how Read/BeginRead works. When you call a synchronous read, you are telling the socket to block until there is data available, and when there is data in the TCP buffer, it will unblock and your receiving buffer will be filled. But even if the Socket receives information while you don't have a Read/BeginRead up, that data will stay in the receive buffer until you call another Read.
nasufara