开发者

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( Add开发者_如何学PythonressFamily.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?


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%?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜