Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket servers, SocketAsyncEventArgs and concurrent connections in .Net

Tags:

.net

tcp

sockets

I've been writing a socket server based around the one on CodeProject which itself derives from the original Microsoft example.

In both cases, the inbound message is immediately returned to the sender using the same SocketAsyncEventArgs. In my case, I need to send the inbound message off for further async processing prior to replying to the client.

The problem is that the returning response may try to use the same SocketAsyncEventArgs at the same time as a further message from the client. When this happens I get this exception:

"An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance"

So, (I believe) I need a separate pool of SocketAsyncEventArgs for messages going back out. All understandable so far.

My problem is that I'm not sure how to create the outbound SocketAsyncEventArgs as it relates closely to the inbound one.

How much of the inbound one can I reuse? e.g. If I just point at the same AcceptSocket, will there be trouble while messages travel in both directions simultaneously?

Does anyone have some example code of how to derive the outbound SocketAsyncEventArgs from the inbound one? Or am I missing the point?

like image 959
Alan Avatar asked Feb 23 '11 15:02

Alan


1 Answers

These SocketAsyncEventArgs objects, you can use them as you please. They serve you. And its almost only about the Socket and the buffer that they use.

So, having that CodeProject article as an example, it makes sense to reuse the same SAEA instance for SendAsync() right after a whole receive (possibly made up of several ReceiveAsync() calls) has completed. The author states the protocol is: each one of the parties involved send and receive in turns.

In your case, it would be simplest to just release the SAEA instance back to the pool after the whole receive completes. Then, later on, after you finished your extra message processing, you can issue a brand new send operation using a freshly popped from the pool SocketAsyncEventArgs object.

Another option would be to just keep passing the SAEA used by the receive operation from callback to callback during your asynchronous processing, and then finally use it for sending back the processed message.

like image 188
Vladimir Avatar answered Oct 07 '22 19:10

Vladimir