Async Sockets

G

Guest

I've written a fair amount of sockets code using the Winsock2 API, but I am having some trouble converting to the .Net Sockets API, specifically asynchronous sockets.

What I have is a form that is both a client and a server. When the form starts I create a listening socket and call Socket.BeginAccept(). When a client connects my accept function is called, and it is on a separate thread. After I accept the client connection I connect to another server (no async there).

Now both sockets call Socket.BeginReceive() and wait for data. When data from one arrives, I log it, then pass it to the other. This seems to work well, however things break down when the client disconnects.

First when a client disconnects I have no way to know about it (in winsock I could get the FD_CLOSE event). So currently I can do nothing in my form, so I added a "Reset" button which seems to cause real unpleasantness.

After a client has disconnected and I click "Reset" in the form, how do I stop all the async receives?

Currently I am calling EndReceive with the IAsyncResult I got from the BeginReceive. But when a new client attempts to connect I get a "Fatal Execution Engine Exception" from code that should be fine. Plus I seem to accumulate more threads than I can explain.

Can anyone recommend a good C# async server example? Or MSDN article?

Thanks!
Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top