简体   繁体   English

听力插座

[英]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: 我遇到了一个奇怪的问题,我之前从未真正解决过这个问题,这里是服务器的代码(在这种情况下客户端是firefox),我创建它的方式:

_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. 所以我期待它挂在listener.Socket.Poll上直到新的连接到来,但是在第一个出现之后,它会永远挂起。 I tried to poll it constantly with smaller delay, let's say 10 microseconds, then it never goes in SelectMode.SelectRead. 我试图以较小的延迟不断地轮询它,比方说10微秒,然后它永远不会进入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? 也许我没有关闭客户端套接字和客户端(firefox)决定使用旧套接字?

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. 我最近在TCPListener回答了类似的问题 ,但是在Socket类上可以使用相同的模式。

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: 我看一下使用.NET反射器的Sockets.TCPListener.Pending()方法,他们有这个,也许你可以试试:

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%? 请记住,根据MSDN, TCPListener.Pending()方法是非阻塞的,因此不确定它是否可以帮助您100%?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM