Sockets - what's the best way to do this?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have an application that listens on a socket using TcpListener. Afiter I
create the object I use the Start method and then I wait for an incoming
request. No problem with this. When waiting for a socket connection the
application is in blocking mode. I can use the Pending method to see if there
are incoming requests before calling AcceptSocket. But that's not what I want
to do as it means my app can spin around in a frantic loop. I could use a
timer but I don't want to if I can avoid it. Ideally I'd like to wait on the
AcceptSocket method like I've used, but just before the connection request
comes in, is there a sort of pre-connection event that gets fired that I can
use? This way, I can wait in blocking mode which is fine but if there is an
event that occurs just before I accept the socket I could use that
information to decide if I really want to accept it or not. An example might
be to allow only 20 connections at any one time for example, or deny
connection requests if a database is out of service, that sort of thing. If
there's no direct event I can trap, then how could I code for this situation
before accepting the socket. By the time I accept the socket, the client
knows it's available but a moment later I may want to prevent the connection
and that means having to Close it, sort of pulling the rug from under the
client applications feet. If I can do this before the client application gets
notifed that the connection was accepted that would be ideal. I don't want to
thrash the system spinning on the Pending method as I've mentioned and it's
not ideal that I use a timer either. In short, how could I handle a
pre-connection notification and if it does not satisfy my criteria reject the
incoming request. Thanks
 
You want to deny the request based on some business rules, but wouldn't it
make sense to tell the client why you are denying the request? That way,
they can respond accordingly. For example, if you are too busy, and you
accept the request, respond with a quick "I'm busy" message and close, then
the client can incorporate logic to try again later. On the other hand, if
the client connects and provides an invalid header or improper credentials,
then you don't want them to keep trying, because the condition is unlikely
to clear up without intervention.

So, I would suggest, first of all, looking at your protocol to see if you
can provide the information to the client about why you want to drop the
connection.

Secondly, use the thread pool to wait for incoming requests. Go ahead and
block on the incoming request and accept it in your threads. No need to
spin on status or use a timer, which you rightfully point out will simply
consume CPU cycles needlessly.

I hope these suggestions are helpful,

--- Nick

"Mr Grunge of Gunk Hall." <Mr Grunge of Gunk
(e-mail address removed)> wrote in message
 
Back
Top