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

后端 未结 2 1247
渐次进展
渐次进展 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.

提交回复
热议问题