~ 1 second TcpListener Wait () / AcceptTcpClient () lag

Maybe just watch this video: http://screencast.com/t/OWE1OWVkO As you can see, the delay between the initiated connection (via telnet or firefox) and my program receives it first.

Here is the code pending connection

    public IDLServer(System.Net.IPAddress addr,int port)
    {
        Listener = new TcpListener(addr, port);

        Listener.Server.NoDelay = true;//I added this just for testing, it has no impact

        Listener.Start();

        ConnectionThread = new Thread(ConnectionListener);
        ConnectionThread.Start();


    }

    private void ConnectionListener()
    {
        while (Running)
        {
            while (Listener.Pending() == false) { System.Threading.Thread.Sleep(1); }//this is the part with the lag
            Console.WriteLine("Client available");//from this point on everything runs perfectly fast 
            TcpClient cl = Listener.AcceptTcpClient(); 

            Thread proct = new Thread(new ParameterizedThreadStart(InstanceHandler));
            proct.Start(cl);


        }

    }

(I had a problem with the code that got into the code block)

I tried a couple of different things, maybe I'm using TcpClient / Listener instead of a raw Socket object? This is not a required TCP thread that I know, and I tried to run everything in one thread, etc.

+2
source share
4 answers

, , .

public IDLServer(System.Net.IPAddress addr,int port)
{
    Listener = new TcpListener(addr, port);

    Listener.Start();        

    // Use the BeginXXXX Pattern to accept clients asynchronously
    listener.BeginAcceptTcpClient(this.OnAcceptConnection,  listener);
}

private void OnAcceptConnection(IAsyncResult asyn) 
{
    // Get the listener that handles the client request.
    TcpListener listener = (TcpListener) asyn.AsyncState;

    // Get the newly connected TcpClient
    TcpClient client = listener.EndAcceptTcpClient(asyn);

    // Start the client work
    Thread proct = new Thread(new ParameterizedThreadStart(InstanceHandler));
    proct.Start(client);

    // Issue another connect, only do this if you want to handle multiple clients
    listener.BeginAcceptTcpClient(this.OnAcceptConnection,  listener);    
}
+3

, - dns-? IP- , DNS? ParmesanCodice , - /.

\system32\drivers\etc\hosts:

127.0.0.1       localhost

127.0.0.1:85

+2

?

, MMO-. , .

, - , , ParmesanCodice (, , , ), , 5-10 , , hammmer , theres no ...

, .

? Throw 1000 , , .

0

You can avoid the entire Listener.Pending while loop. AcceptTcpClient () is a blocking call, so you can just run your code and defer it. I don’t know why this cycle will take 1 second (instead of 1 millisecond), but since you indicate where the lag is, you can get rid of it.

0
source

Source: https://habr.com/ru/post/1744104/


All Articles