开发者

Problem with HTTP Connections

开发者 https://www.devze.com 2023-03-10 18:21 出处:网络
I\'ve a big problem (sorry for my poor english). I attach directly my code: public bool isServerOnline()

I've a big problem (sorry for my poor english). I attach directly my code:

public bool isServerOnline()
{
        Boolean ret = false;

        try
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(VPMacro.MacroUploader.SERVER_URL);
            req.Method = "HEAD";
            req.KeepAlive = false;
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (resp.StatusCode == HttpStatusCode.OK)开发者_开发知识库
            {
                // HTTP = 200 - Internet connection available, server online
                ret = true;
            }
            resp.Close();
            return ret;

        }
        catch (WebException we)
        {
            // Exception - connection not available
            Log.e("InternetUtils - isServerOnline - " + we.Status);
            return false;
        }
}

This function is invoked by a lot of thread and send HEAD requests to a Tomcat Server. So, this method open a connection for each request that I perform and within 10 minutes I've 100 connection active.

How I resolve this problem?


2 things you could do to properly manage a connection:

first:

initialize

HttpWebResponse resp;

before the try statement.

Then close in a finally statement

finally
{ 
    if (resp != null) 
    {
        resp.Close();
    }
}

second:

Try managing your connections with the "using()" clause

using(var a = new connection())
{
    //Your code
}


Tomcat Manager shows sessions, not active TCP connections. Each request might start a new session, but an active session does not necessarily indicate an active TCP connection.

0

精彩评论

暂无评论...
验证码 换一张
取 消