对来自同一主机的http请求不能收到2个以上的响应

时间:2014-09-30 11:04:41

标签: android httpwebrequest xamarin.android

我希望在循环中发送3或4个http请求,并在收到响应时,从每个请求的流中读取数据。问题是总是只收到来自回复的2个。

protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        SetContentView (Resource.Layout.Main);
        Button button = FindViewById<Button> (Resource.Id.myButton);

        button.Click += delegate 
        {
            Task.Run(() => this.DoRequestData());
            Task.Run(() => this.DoRequestData());
            Task.Run(() => this.DoRequestData());
            Task.Run(() => this.DoRequestData());
        };
    }

    private void DoRequestData()
    {
        // !!! problem occurs if URL contains SAME ip and port and ANY OTHER path !!!
        var reqPath = "http://10.0.10.96:80/path";
        WebRequest request = WebRequest.Create(reqPath);

        HttpWebRequest httpRequest = request as HttpWebRequest;

        request.BeginGetResponse (res => this.OnResponse(res), request);
    }

    private void OnResponse (IAsyncResult result)
    {
        WebRequest request = (WebRequest)result.AsyncState;
        string reqStr = request.RequestUri.ToString ();

        WebResponse response;
        BinaryReader dataReader;

        if (TryGetResponseOrError (result, out response, reqStr)) 
        {
            while(true)
            {
                byte[] bytes = dataReader.ReadBytes(200);

                if(bytes.Length != 200)
                {
                    return;
                }
            }
        } 
    }

    private static bool TryGetResponseOrError (IAsyncResult result, out WebResponse response, string reqStr)
    {
        response = null;

        try
        {
            WebRequest request = (WebRequest)result.AsyncState;
            response = request.EndGetResponse (result);
            return true;
        }
        catch(WebException ex) 
        {

        }

        return false;
    }

无论发送了多少请求,回调方法OnResponse总是只被调用2次。该代码包含在便携式库中,在iOS中完美运行(通过Xamarin.IOS)。请帮助。

1 个答案:

答案 0 :(得分:0)

Xamarin的支持团队将其发布为错误:https://bugzilla.xamarin.com/show_bug.cgi?id=23541