Network Sockets Question

  • Thread starter Thread starter jm
  • Start date Start date
J

jm

I have a client and a server (of course). The listener, from the code
I got on Microsoft (MSDN) uses a While (true) to wait on accepting a
socket. When the message sent to the listener application is
complete, the message is processed and the While loop, since true,
goes back and waits for another socket.

The problem I have is that there are other functions and procedures
that are called within this loop. They are never being activated
because the While(true) is always running. The calls are in the
middle of the while loop:

While (true)
{

if (x==y)
{
call_this_procedure(); //may get called, but never works; have
stepped thorough it seen that it hits this, it just doesn't work; take
out the While(true) and it works;
}
}

but that "call_this_procedure()" never works. If I take out the
While(true) it works.

Someone told me I needed to use async sockets. Again, using MSDN, I
was able to get some code working, but the result was the same.
Again, they had the listener in the While(true) construct. I cannot
get things to work right this way. Can someone please advise. Thank
you for any help.
 
jm, what are you doing in the call_this_procedure()? Have you tried
executing a simple function in there which just prints something out or
other trivial task? Do you get an error?
 
Jim,

If you're doing the following:

while(true)
{
Socket client = serverSocket.Accept();

if (x == y)
{
DoSomething();
}
}

Then of course your method won't fire until a socket is actually accepted.
If you have other methods that need to fire continually on the same thread
as the listening socket, you should use the Poll() method, like so:

while(true)
{
if (serverSocket.Poll(1000000, SelectMode.SelectRead))
{
Socket client = serverSocket.Accept();
...do whatever with the client, spawn a worker thread, etc...
}

if (x == y)
{
DoSomething();
}
}

The Poll method will poll the server socket for 1 second (the 1000000 is
microseconds) to see if it can read from it (in this case, a read would mean
that a client has connected). If it can read, the code accepts the client
and continues on its merry way. If it can't read, the poll will timeout and
continue on to the "if (x == y)" part, which will then loop back around
eventually and poll the server socket again.

Alternatively, if you do wish to use asyncronous sockets, you can use
BeginAccept instead and register a delegate that will be called when a
client connects, which will then get executed on a different thread.

-Brian Newtz
 
Back
Top