tags:

views:

137

answers:

1
+3  Q: 

Listening socket

I got a strange problem, I never actually expirienced this before, here is the code of the server (client is firefox in this case), the way I create it:

_Socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
_Socket.Bind( new IPEndPoint( Settings.IP, Settings.Port ) );
_Socket.Listen( 1000 );
_Socket.Blocking = false;

the way i accept connection:

while( _IsWorking )
{
    if( listener.Socket.Poll( -1, SelectMode.SelectRead ) )
    {
        Socket clientSocket = listener.Socket.Accept();
        clientSocket.Blocking = false;
        clientSocket.SetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true );
    }
}

So I'm expecting it hang on listener.Socket.Poll till new connection comes, but after first one comes it hangs on poll forever. I tried to poll it constantly with smaller delay, let's say 10 microseconds, then it never goes in SelectMode.SelectRead. I guess it maybe somehow related on client's socket reuse? Maybe I don't shutdown client socket propertly and client(firefox) decides to use an old socket?

I disconnect client socket this way:

Context.Socket.Shutdown( SocketShutdown.Both ); // context is just a wrapper around socket
Context.Socket.Close();

What may cause that problem?

+1  A: 

Have you considered accepting remote clients asynchronously? I answered a similar question recently on TCPListener, but the same pattern can be used for on the Socket Class.

I have never seen this used before to check if a client is available to connect:

listener.Socket.Poll( -1, SelectMode.SelectRead ) )

I had a look inside the Sockets.TCPListener.Pending() method using .NET reflector and they have this instead, maybe you can try it:

public bool Pending()
{
    if (!this.m_Active)
    {
        throw new InvalidOperationException(SR.GetString("net_stopped"));
    }
    return this.m_ServerSocket.Poll(0, SelectMode.SelectRead);
}

Just bear in mind that according to MSDN the TCPListener.Pending() method is non-blocking so not sure if it helps you 100%?

ParmesanCodice
I think I found the reason for behavour I described, this was that I didn't disconnect client socket after it's being processed and after that new connection for some reason could not be made, I guess it's some how related to the client's (firefox in this case) desire to use one socket (if it wasn't closed by server) till it's possible.
hoodoos
actually that guy in the question you mentioned did it completely wrong :) and i actually didn't mention he had sleep between pending checks, i dunno really for which purpose he was doing this listening in non-blocking manner..
hoodoos