使用Volley请求的随机延迟

时间:2017-01-05 09:00:53

标签: android android-volley nanohttpd

我正在使用Volley singleton向使用java制作的NanoHTTPD服务器发送POST消息。消息很短,处理时间很快,同时消息不超过1条。

问题是随机队列中有一些延迟来处理请求,产生的加载时间为3-4秒。最常见的情况是第一条消息(这没有问题,我想是在做一些实例)或者在任何消息之后等待超过5-10秒。但是,如果我发送,例如100个POST消息与1秒之间的延迟没有问题。

我检查了服务器并且没有生成请求,因此问题出在客户端。

在这些情况下, logcat 显示:

  

D / Volley:[839] BasicNetwork.logSlowRequests:HTTP响应   request =< [] http://192.168.2.8:8765 0x355fcdd NORMAL 1>   [lifetime = 4768],[size = 115],[rc = 200],[retryCount = 0]

执行一些谷歌 logSlowRequests 意味着......请求需要时间在客户端进行处理。

尝试的另一个解决方案是增加 threadPoolSize ,但这不起作用。总是第一个请求需要花费很多时间。

这是单身人士代码:

public class VolleySingleton {

    private static VolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private static Context mCtx;
    private DiskBasedCache cache;
    private BasicNetwork network;

    /**
     * @param context
     */
    private VolleySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();
    }

    /**
     * @param context
     * @return
     */
    public static synchronized VolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleySingleton(context);
        }
        return mInstance;
    }

    /**
     * @return
     */
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // Instantiate the cache
            cache = new DiskBasedCache(mCtx.getCacheDir(), 1024 * 1024); // 1MB cap
            // Set up the network to use HttpURLConnection as the HTTP client.
            network = new BasicNetwork(new HurlStack());
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = new RequestQueue(cache, network, 20);
            mRequestQueue.start();
        }
        return mRequestQueue;
    }

    /**
     * @param req
     * @param <T>
     */
    public <T> void addToRequestQueue(Request<T> req) {
        req.setRetryPolicy(new DefaultRetryPolicy(
                30000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        getRequestQueue().add(req);
    }

}

1 个答案:

答案 0 :(得分:0)

更深入的调试和问题是服务器:

    this.remoteHostname = !inetAddress.isLoopbackAddress() && !inetAddress.isAnyLocalAddress()?inetAddress.getHostName().toString():"localhost";

这会生成需要几秒钟的DNS查找。

库github项目中已经上传了一个问题:

https://github.com/NanoHttpd/nanohttpd/issues/396