Home > Software design >  C# Using Socket.Receive(bytes) takes about 3 minutes
C# Using Socket.Receive(bytes) takes about 3 minutes

Time:12-05

I am using .NET 6.0 and recently using int numBytes = client.Receive(bytes); has been taking around about 3 minutes. The Socket variable is called client. This issue was not occuring 3 days ago.

The full code that I am using is:

string data = "";
byte[] bytes = new byte[2048];

client = httpServer.Accept();
// Read inbound connection data
while (true)
{
    int numBytes = client.Receive(bytes); // Taking about 3 minutes here
    data  = Encoding.ASCII.GetString(bytes, 0, numBytes);

    if (data.IndexOf("\r\n") > -1 || data == "")
    {
        break;
    }
}

The timing is also not always consistent. Sometimes (rarely) it can be instant and othertimes it can take 3 minutes - 1 hour.

I have attempted the following:

  • Restarting my computer
  • Changing networks
  • Turning off the firewall
  • Attempting on a different computer
  • Attempting on a different computer with the firewall off
  • Using a wired and wireless connection However none of these worked and instead resulted in the same issue. What I expect to happen and what used to happen is that it would continue through the code normally instead of being hung up on 1 line of code for a long time.

CodePudding user response:

You could use the client.Poll() method to check if data is available to be read from the socket before calling client.Receive().

If client.Poll() returns false, it means that there is no data available to be read and you can handle that situation accordingly.

  • Related