Simple TcpListener hanging

2019-09-05 05:41发布

问题:

Here's the code I'm trying: (This is just for learning how TCP works.) On my PC:

listener = new TcpListener(IPAddress.Any, 3000);
listener.Start();
using (TcpClient client = listener.AcceptTcpClient())
...

And on the server in the event handler of an asp.net button:

using (var wc = new MyWebClient())
{
    byte[] received = wc.UploadData("http://my ip here:3000", new byte[] { 1 });
    Label1.Text = Encoding.UTF8.GetString(received);
}

I disable all firewalls, run the first code on my PC, then click on the button of the page (in my browser) to run the second code.

The first one just waits on its last line. Why? It should be receiving a request.

If there's a better way to receive requests on a PC (e.g. like a web page) I'd like to hear about it.

Edit:

MyWebClient is simply a WebClient with a limited Timeout:

class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest request = base.GetWebRequest(uri);
        request.Timeout = 10 * 1000;
        return request;
    }
}