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

若如初见. 提交于 2019-12-02 01:29:57
Yuval Itzchakov

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!