Using TcpListener.AcceptSocket(); in a separate thread causes the thread to block?

后端 未结 2 1246
渐次进展
渐次进展 2021-01-21 12:00

I have tried to work around this as well as debug but I\'m at a loose end here :( is there any alternative to using this to check for a client connection? This code works fine i

相关标签:
2条回答
  • 2021-01-21 12:39

    It's supposed to block. It can never return null. (Why is everybody doing this? It's like nobody on the web uses Accept correctly.)

    Your problem is that after accepting one connection you process that connection and do nothing to resume accepting. The standard pattern is:

    while (true) {
     var connectionSocket = listeningSocket.Accept();
     ProcessAsynchronously(connectionSocket);
    }
    

    Make sure ProcessAsynchronously returns immediately. Start a new Task or use async/await.

    As you never exit the while loop you never get to sending data. Move all processing logic into ProcessAsynchronously.

    0 讨论(0)
  • 2021-01-21 12:43

    It is supposed to block. From MSDN:

    AcceptSocket is a blocking method that returns a Socket that you can use to send and receive data. If you want to avoid blocking, use the Pending method to determine if connection requests are available in the incoming connection queue.

    You can turn your whole implementation to use the async version: AcceptSocketAsync. Note this wont block your method, it will yield control back to the caller until a new Socket has been connected.

    private async void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        await WorkingAsync();
    }
    

    And inside WorkingAsync:

    private Task WorkingAsync
    {
        // Do all other stuff,
    
        Socket socket = await myList.AcceptSocketAsync();
    
       // Do rest of stuff with the socket
    }
    

    I recommend you like at What is the async/await equivalent of a ThreadPool server? for a full implementation of an async tcp connection handler

    0 讨论(0)
提交回复
热议问题