MDA/MDD/TDD/DDD/DDDDDDD
posts - 536, comments - 111, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

浏览器默认对同一域下的资源,只允许保持一定的连接数,这里的域应该是支持二级域,
浏览器默认最大并发连接数
浏览器HTTP 1.1HTTP 1.0
IE 6,724
IE 866
Firefox 228
Firefox 366
Safari 3, 444
Chrome 1,26?
Chrome 344
Opera 9.63,10.00alpha44

http协议无状态,无连接。无连接的含义就是限制每次连接只处理一个请求,收到应答后即断开。但据说这个是http1.0。   
http1.1里,提出了持久连接(persistent connection)的概念,也就是说同一条 HTTP连接,可以依次处理多个请求。

突然想到,ajax的异步是相对这个浏览器而言,就ajax的这个请求来说,还是同步的。

参考:
http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections/
主流浏览器并发连接数
网站的最大并发连接数
各个浏览器并发连接数比较

posted @ 2010-04-14 18:32 leekiang 阅读(2119) | 评论 (0)编辑 收藏

Adding Socket Timeout to java.net.URLConnection (JDK 1.2)

found a bug , see "connected = true;" in public void connect() throws IOException {


Note: 05/11/01 Sam Found a patch for borland

As I got the email:

Just writing to inform you theis patch for 1.3 works with the 1.3 shipped with borland JBuilder 4 (not sure which excat version it is)

the only problems I had where that the code was a bit messed up, following are the changes made to it to make it work.

				
public void SetTimeout(int i)
throws SocketException
{
this.timeout = i; // Should be i not -1 <------------ERROR
serverSocket.setSoTimeout(i) ;
}

public boolean parseHTTP(MessageHeader header, ProgressEntry entry)
throws java.io.IOException
{
if( this.timeout != -1 ) {
try {
serverSocket.setSoTimeout(timeout) ; // should be timeout not i <---------------ERROR
} catch( SocketException e ) {
throw new java.io.IOException("unable to set socket timeout!") ;
}
}

return super.parseHTTP(header, entry) ;
}
Sam

Under JDK 1.3, which is HTTP 1.1 compatible, the InterruptedIOException gets caught by the socket I/O routines and ignored. input is read in "chunks". I debugged the existing code under 1.3, the Timeout is getting set properly etc., but the exception gets caught in the underlying I/O routines, which have a single retry if any IOExceptions are thrown. Thanks a lot Sun....

3/22/01: Patch for JDK 1.3 unverified

Patch code for JDK 1.3 from Matt Ho (unverified)

				
----[ snip ]----

import sun.net.www.MessageHeader ;
import sun.net.ProgressEntry ;

.
.
.

private int timeout = -1 ;

public void SetTimeout(int i)
throws SocketException
{
this.timeout = -1 ;
serverSocket.setSoTimeout(i) ;
}

public boolean parseHTTP(MessageHeader header, ProgressEntry entry)
throws java.io.IOException
{
if( this.timeout != -1 ) {
try {
serverSocket.setSoTimeout(i) ;
} catch( SocketException e ) {
throw new java.io.IOException("unable to set socket timeout!") ;
}
}

return super.parseHTTP(header, entry) ;
}

----[ snip ]----

On with the rest of the stuff

The BSD socket API supports a timeout option (the option is SO_TIMEOUT), which is also supported in java.net.socket. Unfortunately, java.net.URLConnection does not expose the underlying socket. So if you have a URL connection that attempts to connect to a dead URL (i.e., the URL is well formed and exists but the site is down), the socket will eventually timeout using the operating system's default timeout (420 seconds on Win NT). The timeout is a very long time, e.g., for spiders or URL checking.

The following files illustrate a technique to introduce a socket timeout to URL connection, based upon the actual java source code itself (see the open source community licensing at JavaSoft).

The Base classes, or URLConnection internals

Java's implementation of networking is protocol independent, as well as object oriented. Therefore the implementation is not as straightfoward as one might imagine.

URLConnection relies upon several internal classes using a client/server model as well as a "factory" design pattern. The client's base class is sun.net.www.http.HttpClient. This class is extended for the purpose of exposing the socket.

The default factory is URLStreamHandlerFactory, which indirectly "handles" the creation of an HTTP client by instantiating a class that is specific to the HTTP protocol: sun.net.www.protocol.http.Handler. The handler actually creates the client.

In practice, the factory is only necessary to mimic java's implementation, but only the Handler is really needed.

Derived Classes

We derive 4 classes so as to preserve the symmetry with the java source code:

HttpURLConnectionTimeout extends sun.net.www.protocol.http.HttpURLConnection
HttpTimeoutHandler extends sun.net.www.protocol.http.Handler
HttpTimeoutFactory implements java.net.URLStreamHandlerFactory
HttpClientTimeout extends sun.net.www.http.HttpClient

On with the source code.


HttpURLConnectionTimeout

// whatever package you want
import sun.net.www.http.HttpClient;
import java.net.*;
import java.io.*;
public class HttpClientTimeout extends HttpClient
{
public HttpClientTimeout(URL url, String proxy, int proxyPort) throws IOException
{
super(url, proxy, proxyPort);
}

public HttpClientTimeout(URL url) throws IOException
{
super(url, null, -1);
}

public void SetTimeout(int i) throws SocketException {
serverSocket.setSoTimeout(i);
}

/* This class has no public constructor for HTTP. This method is used to
* get an HttpClient to the specifed URL. If there's currently an
* active HttpClient to that server/port, you'll get that one.
*
* no longer syncrhonized -- it slows things down too much
* synchronize at a higher level
*/
public static HttpClientTimeout GetNew(URL url)
throws IOException {
/* see if one's already around */
HttpClientTimeout ret = (HttpClientTimeout) kac.get(url);
if (ret == null) {
ret = new HttpClientTimeout (url); // CTOR called openServer()
} else {
ret.url = url;
}
// don't know if we're keeping alive until we parse the headers
// for now, keepingAlive is false
return ret;
}

public void Close() throws IOException
{
serverSocket.close();
}

public Socket GetSocket()
{
return serverSocket;
}


}

HttpTimeoutFactory

import java.net.*;

public class HttpTimeoutFactory implements URLStreamHandlerFactory
{
int fiTimeoutVal;
public HttpTimeoutFactory(int iT) { fiTimeoutVal = iT; }
public URLStreamHandler createURLStreamHandler(String str)
{
return new HttpTimeoutHandler(fiTimeoutVal);
}

}

HttpTimeoutHandler

import java.net.*;
import java.io.IOException;

public class HttpTimeoutHandler extends sun.net.www.protocol.http.Handler
{
int fiTimeoutVal;
HttpURLConnectionTimeout fHUCT;
public HttpTimeoutHandler(int iT) { fiTimeoutVal = iT; }

protected java.net.URLConnection openConnection(URL u) throws IOException {
return fHUCT = new HttpURLConnectionTimeout(u, this, fiTimeoutVal);
}

String GetProxy() { return proxy; } // breaking encapsulation
int GetProxyPort() { return proxyPort; } // breaking encapsulation

public void Close() throws Exception
{
fHUCT.Close();
}

public Socket GetSocket()
{
return fHUCT.GetSocket();
}
}

HttpURLConnectionTimeout

import java.net.*;
import java.io.*;
import sun.net.www.http.HttpClient;

public class HttpURLConnectionTimeout extends sun.net.www.protocol.http.HttpURLConnection
{
int fiTimeoutVal;
HttpTimeoutHandler fHandler;
HttpClientTimeout fClient;
public HttpURLConnectionTimeout(URL u, HttpTimeoutHandler handler, int iTimeout) throws IOException
{
super(u, handler);
fiTimeoutVal = iTimeout;
}

public HttpURLConnectionTimeout(URL u, String host, int port) throws IOException
{
super(u, host, port);
}

public void connect() throws IOException {
if (connected) {
return;
}
try {
if ("http".equals(url.getProtocol()) /* && !failedOnce <- PRIVATE */ ) {
// for safety's sake, as reported by KLGroup
synchronized (url)
{
http = HttpClientTimeout.GetNew(url);
}
fClient = (HttpClientTimeout)http;
((HttpClientTimeout)http).SetTimeout(fiTimeoutVal);
} else {
// make sure to construct new connection if first
// attempt failed
http = new HttpClientTimeout(url, fHandler.GetProxy(), fHandler.GetProxyPort());
}
ps = (PrintStream)http.getOutputStream();
} catch (IOException e) {
throw e; }
// this was missing from the original version
connected = true;
}

/**
* Create a new HttpClient object, bypassing the cache of
* HTTP client objects/connections.
*
* @param url the URL being accessed
*/
protected HttpClient getNewClient (URL url)
throws IOException {
HttpClientTimeout client = new HttpClientTimeout (url, (String)null, -1);
try {
client.SetTimeout(fiTimeoutVal);
} catch (Exception e)
{ System.out.println("Unable to set timeout value"); }
return (HttpClient)client;
}

/**
* opens a stream allowing redirects only to the same host.
*/
public static InputStream openConnectionCheckRedirects(URLConnection c)
throws IOException
{
boolean redir;
int redirects = 0;
InputStream in = null;

do {
if (c instanceof HttpURLConnectionTimeout) {
((HttpURLConnectionTimeout) c).setInstanceFollowRedirects(false);
}

// We want to open the input stream before
// getting headers, because getHeaderField()
// et al swallow IOExceptions.
in = c.getInputStream();
redir = false;

if (c instanceof HttpURLConnectionTimeout) {
HttpURLConnectionTimeout http = (HttpURLConnectionTimeout) c;
int stat = http.getResponseCode();
if (stat >= 300 && stat <= 305 &&
stat != HttpURLConnection.HTTP_NOT_MODIFIED) {
URL base = http.getURL();
String loc = http.getHeaderField("Location");
URL target = null;
if (loc != null) {
target = new URL(base, loc);
}
http.disconnect();
if (target == null
|| !base.getProtocol().equals(target.getProtocol())
|| base.getPort() != target.getPort()
|| !HostsEquals(base, target)
|| redirects >= 5)
{
throw new SecurityException("illegal URL redirect");
}
redir = true;
c = target.openConnection();
redirects++;
}
}
} while (redir);
return in;
}

// Same as java.net.URL.hostsEqual


static boolean HostsEquals(URL u1, URL u2)
{
final String h1 = u1.getHost();
final String h2 = u2.getHost();

if (h1 == null) {
return h2 == null;
} else if (h2 == null) {
return false;
} else if (h1.equalsIgnoreCase(h2)) {
return true;
}
// Have to resolve addresses before comparing, otherwise
// names like tachyon and tachyon.eng would compare different
final boolean result[] = {false};

java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
try {
InetAddress a1 = InetAddress.getByName(h1);
InetAddress a2 = InetAddress.getByName(h2);
result[0] = a1.equals(a2);
} catch(UnknownHostException e) {
} catch(SecurityException e) {
}
return null;
}
});

return result[0];
}

void Close() throws Exception
{
fClient.Close();
}

Socket GetSocket()
{
return fClient.GetSocket();
}
}

Sample Usage #1

import java.net.*;
public class MainTest
{

public static void main(String args[])
{
int i = 0;
try {
URL theURL = new URL((URL)null, "http://www.snowball.com", new HttpTimeoutHandler(150)); // timeout value in milliseconds

// the next step is optional
theURL.setURLStreamHandlerFactory(new HttpTimeoutFactory(150));


URLConnection theURLconn = theURL.openConnection();
theURLconn.connect();
i = theURLconn.getContentLength();
}
catch (InterruptedIOException e)
{
System.out.println("timeout on socket");
}
System.out.println("Done, Length:" + i);
}
}

Sample Usage #2

		try
{
HttpTimeoutHandler xHTH = new HttpTimeoutHandler(10); // timeout value in milliseconds
URL theURL = new URL((URL)null, "http://www.javasoft.com", xHTH);
HttpURLConnection theUC = theURL.openConnection();
.
.
.
}
catch (InterruptedIOException e)
{
// socket timed out

}

Some remarks: this code is thread safe.

More to come

来源:http://www.logicamente.com/sockets.html

     http://www.edevs.com/java-programming/15068/


Thanks Felipe!

If I understand information at http://www.logicamente.com/sockets.html correctly there are 2 problems with timeout when using HttpURLConnection in JDK 1.3:

1. HttpURLConnection does not allow changing the default timeout that is in order of few minutes.

2. If actual HTTP stream is chunked then HttpURLConnection ignores even the default timeout and tries to read what it perceives as a continued stream resulting in indefinite read wait.

The patch shown at the above URL, consisting of subclassing of 4 system classes (1 from java.net... and 3 from sun.net.www...), is aimed to resolve problem 1 above but does not help in problem 2.

My main problem is to have timeout when reading chunked stream (system default timeout will be ok to beginning with) and therefore the question is if this bug has been corrected in later versions of JDK? Thanks.

-----

I have seen much chat about this "problem", that is setSoTimeout not available or not working properly.

how about you write your own Timer (resettable) or 1.4 has Timer class

you just reset it anytime you detect network activity and close the Socket if the Timer finishes its cycle?

posted @ 2010-04-14 17:09 leekiang 阅读(2335) | 评论 (0)编辑 收藏

From: Niels Campbell (niels_campbell_at_lycos.co.uk)
Date: 01/23/04
Date: 23 Jan 2004 09:14:16 -0800
After spending nearly 3 days on this problem to come up with a

solution I think it is only right to post the solution.

I found that you can't set the soTimeout on an HttpURLConnection as
the sockets are encapsulated within the HttpURLConnection
implementation.

I found Mike Reiche solution in which he uses a handler to set a
timeout value. This nearly worked. Looking at the code in the rt.jar I
found that the initial timeout was working, but the call
parseHTTP(...) in HttpClient was then attempting a second connection
which had a time out value of 0(infinite).

I modified the code to override the doConnect() in the NetworkClient
and managed to get a timeout occurring. To be exact two timeouts
occur.

It works on
java version "1.4.0_03"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0_03-b04)
Java HotSpot(TM) Client VM (build 1.4.0_03-b04, mixed mode)
and
java version "1.2.2"
Classic VM (build JDK-1.2.2_013, native threads, symcjit)

Anyway here is the code, excuse the formatting.

/* HttpTimeoutURLConnection.java */
import java.net.*;
import java.io.*;
import sun.net.www.http.HttpClient;

// Need to override any function in HttpURLConnection that create a
new HttpClient
// and create a HttpTimeoutClient instead. Those functions are
// connect(), getNewClient(), getProxiedClient()

public class HttpTimeoutURLConnection extends
sun.net.www.protocol.http.HttpURLConnection
{

    public HttpTimeoutURLConnection(URL u, HttpTimeoutHandler handler,
int iSoTimeout)
        throws IOException
    {
        super(u, handler);
        HttpTimeoutClient.setSoTimeout(iSoTimeout);
    }

    public void connect() throws IOException
    {
        if (connected)
        {
            return;
        }

        try
        {
            if ("http".equals(url.getProtocol())) // && !failedOnce <-
PRIVATE
            {
                // for safety's sake, as reported by KLGroup
                synchronized (url)
                {
                    http = HttpTimeoutClient.getNew(url);
                }
            }
            else
            {
                if (handler instanceof HttpTimeoutHandler)
                {
                    http = new HttpTimeoutClient(super.url,
((HttpTimeoutHandler)handler).getProxy(),
((HttpTimeoutHandler)handler).getProxyPort());
                }
                else
                {
                    throw new IOException("HttpTimeoutHandler
expected");
                }
            }

            ps = (PrintStream)http.getOutputStream();
        }
        catch (IOException e)
        {
            throw e;
        }

        connected = true;
    }

    protected HttpClient getNewClient(URL url)
        throws IOException
    {
        HttpTimeoutClient httpTimeoutClient = new HttpTimeoutClient
(url, (String)null, -1);
        return httpTimeoutClient;
    }

    protected HttpClient getProxiedClient(URL url, String s, int i)
        throws IOException
    {
        HttpTimeoutClient httpTimeoutClient = new HttpTimeoutClient
(url, s, i);
        return httpTimeoutClient;
    }

}

/* HttpTimeoutHandler.java */
import java.net.*;
import java.io.IOException;

public class HttpTimeoutHandler extends
sun.net.www.protocol.http.Handler
{
    private int iSoTimeout=0;

    public HttpTimeoutHandler(int iSoTimeout)
    {
        // Divide the time out by two because two connection attempts
are made
        // in HttpClient.parseHTTP()

        if (iSoTimeout%2!=0)
        {
            iSoTimeout++;
        }
        this.iSoTimeout = (iSoTimeout/2);
    }

    protected java.net.URLConnection openConnection(URL u) throws
IOException
    {
        return new HttpTimeoutURLConnection(u, this, iSoTimeout);
    }

    protected String getProxy()
    {
        return proxy;
    }

    protected int getProxyPort()
    {
        return proxyPort;
    }
}

/* HttpTimeoutFactory.java */
import java.net.*;

public class HttpTimeoutFactory implements URLStreamHandlerFactory
{
    private int iSoTimeout=0;

    public HttpTimeoutFactory(int iSoTimeout)
    {
        this.iSoTimeout = iSoTimeout;
    }

    public URLStreamHandler createURLStreamHandler(String str)
    {
        return new HttpTimeoutHandler(iSoTimeout);
    }
}

/* HttpTimeoutClient.java */
import sun.net.www.http.HttpClient;
import java.net.*;
import sun.net.*;
import sun.net.www.*;
import java.io.*;

public class HttpTimeoutClient extends HttpClient
{
    private static int iSoTimeout=0;

    public HttpTimeoutClient(URL url, String proxy, int proxyPort)
throws IOException
    {
        super(url, proxy, proxyPort);
    }

    public HttpTimeoutClient(URL url) throws IOException
    {
        super(url, null, -1);
    }

    public static HttpTimeoutClient getNew(URL url)
        throws IOException
    {
        HttpTimeoutClient httpTimeoutClient = (HttpTimeoutClient)
kac.get(url);

        if (httpTimeoutClient == null)
        {
            httpTimeoutClient = new HttpTimeoutClient (url); // CTOR
called openServer()
        }
        else
        {
            httpTimeoutClient.url = url;
        }

        return httpTimeoutClient;
    }

    public static void setSoTimeout(int iNewSoTimeout)
    {
        iSoTimeout=iNewSoTimeout;
    }

    public static int getSoTimeout()
    {
        return iSoTimeout;
    }

    // Override doConnect in NetworkClient

    protected Socket doConnect(String s, int i)
        throws IOException, UnknownHostException, SocketException
    {
        Socket socket=super.doConnect(s,i);

        // This is the important bit
        socket.setSoTimeout(iSoTimeout);
        return socket;
    }

}

/* Example use */
import java.util.*;
import java.io.*;
import java.net.*;

public class SystemProperty
{
    public static void main(String[] args)
    {
        String sSoapUrl="http://192.168.0.223/mobaqSecurity/SslTunnelServlet";
        System.out.println("Connecting to [" + sSoapUrl + "]");

        URLConnection urlConnection = null;
        URL url=null;

        try
        {
            url = new URL((URL)null, sSoapUrl, new
HttpTimeoutHandler(10000));
            urlConnection = url.openConnection();

            // Optional
            url.setURLStreamHandlerFactory(new
HttpTimeoutFactory(10000));

            System.out.println("Url class
["+urlConnection.getClass().getName()+"]");
        }
        catch (MalformedURLException mue)
        {
            System.out.println(">>MalformedURLException<<");
            mue.printStackTrace();
        }
        catch (IOException ioe)
        {
            System.out.println(">>IOException<<");
            ioe.printStackTrace();
        }

        HttpURLConnection httpConnection =
(HttpURLConnection)urlConnection;
        System.out.println("Connected to [" + sSoapUrl + "]");

        byte[] messageBytes=new byte[10000];
        for (int i=0; i<10000; i++)
        {
            messageBytes[i]=80;
        }

        try
        {
            httpConnection.setRequestProperty("Connection", "Close");
            httpConnection.setRequestProperty("Content-Length",
String.valueOf(messageBytes.length));
            httpConnection.setRequestProperty("Content-Type",
"text/xml; charset=utf-8");
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
        }
        catch (ProtocolException pe)
        {
            System.out.println(">>ProtocolException<<");
            pe.printStackTrace();
        }

        OutputStream outputStream=null;

        try
        {
            System.out.println("Getting output stream");
            outputStream =httpConnection.getOutputStream();
            System.out.println("Got output stream");

            outputStream.write(messageBytes);
        }
        catch (IOException ioe)
        {
            System.out.println(">>IOException<<");
            ioe.printStackTrace();
        }

        try
        {
            System.out.println("Getting input stream");
            InputStream is=httpConnection.getInputStream();
            System.out.println("Got input stream");

            byte[] buf = new byte[1000];
            int i;

            while((i = is.read(buf)) > 0)
            {
                System.out.println(""+new String(buf));
            }
            is.close();
        }
        catch (Exception ie)
        {
            ie.printStackTrace();
        }

    }
}

Cheers,
Niels

来源:http://coding.derkeiler.com/Archive/Java/comp.lang.java.programmer/2004-01/3271.html
     http://www.weblogicfans.net/viewthread.php?tid=1101
     http://forums.sun.com/thread.jspa?threadID=568948
备注:在HttpTimeoutClient类中的第二个构造函数中的:super(url,null,-1)改为super(url, (String)null,-1)即可。

posted @ 2010-04-14 17:04 leekiang 阅读(1326) | 评论 (0)编辑 收藏

System.setProperty("sun.net.client.defaultConnectTimeout", "500");
System.setProperty("sun.net.client.defaultReadTimeout", "500");
在jdk1.4.2_05下测http,上面的代码是生效的,https没有试。
好像jdk1.4.2.12解决了https的问题,见jdk1.4的bug清单。
HttpURLConnection的实现类正常情况下是sun.net.www.protocol.http.HttpURLConnection
而weblogic8下是weblogic.net.http.SOAPHttpURLConnection。
SOAPHttpURLConnection是weblogic.net.http.HttpURLConnection的子类
System.setProperty("weblogic.client.SocketConnectTimeoutInSecs", "500");在sp4不管用
-Dweblogic.client.SocketConnectTimeoutInSecs=500也不管用。

在http://forums.oracle.com/forums/thread.jspa?threadID=766767里有人说
Well, it depends on the OS and JVM used. If Weblogic is using Native library (socket Muxer) for remote communication then socketconnectTimeout only helps when thread is stuck on "Socket.connect() method, but it would never timeout the socket if it is stuck on "Socket.read()" because the Control does not return to JVM till OS level TCP/IP connection returns.
To resolve this issue, try to timeout TCP connections at OS level using OS parameters. Hopefully BEA would come with some resolution of this issue in future release

应该使用"weblogic.http.client.defaultConnectTimeout"属性
在weblogic9的weblogic.net.http.HttpURLConnection类里找到如下的代码
defaultConnectTimeout = Integer.getInteger("weblogic.http.client.defaultConnectTimeout", -1).intValue();
而在weblogic8.1 sp4的该类里没找到,或许sp5就有了(见http://download.oracle.com/docs/cd/E13222_01/wls/docs81///javadocs/weblogic/net/http/HttpURLConnection.html)

  现在的问题是,对于这种问题可不可以通过超时设定来释放线程。weblogic中,RJVM(即server之间,可能是admin-to- managed,也可能是managed-to-managed)之间,连接的协议有两类五种,两类是http、t3,五种是http、https、 t3、t3s、local。超时设定时协议层面的东西,所以我们这里只讨论http和t3。

       对于t3,从上面的trace可以看到,连接的创建从ServerURL.findOrCreateRJVM()开始,这个方法有多种实现,不同的实现使用不同的timeout,客户端程序可以通过向environment中set一个叫做weblogic.jndi.requestTimeout的变量,如果不做设定,则使用系统默认的DEFAULT_CONNECTION_TIMEOUT,这是个静态值(0)。而在上面的stacktrace中,我们可以看到,environment是在RemoteChannelServiceImpl中定义的,这个environment对于客户而言是不可配置的,而weblogic自己的这个env中是不设定requesttimeotu的,也就是,无论哪种方式,connectionTimeout/readTimeout对于t3,都是不可配置的,而且默认是没有超时的。

        而对于http,HTTPClientJVMConnection在创建HttpURLConnection的时候,会读取系统环境变量中的如下两个变量,
[b]weblogic.http.client.defaultReadTimeout[/b]
[b]weblogic.http.client.defaultConnectTimeout[/b]
        如果没有设定,这两个变量的默认值均为-1,即不做timeout。如果我们作了设定,这两个值即读超时、连接超时都会生效。这两个值可以用于解决上述的问题。
        weblogic.http.client.defaultReadTimeout
weblogic.http.client.defaultConnectTimeout

哪里可以设置呢?
举例:
Windows平台:
set JAVA_OPTIONS=-Dweblogic.http.client.defaultReadTimeout=30 -Dweblogic.http.client.defaultConnectTimeout=30 %JAVA_OPTIONS%
UNIX/Linux平台:
JAVA_OPTIONS="-Dweblogic.http.client.defaultReadTimeout=30 -Dweblogic.http.client.defaultConnectTimeout=30 $JAVA_OPTIONS"
export JAVA_OPTIONS

posted @ 2010-04-14 16:59 leekiang 阅读(4172) | 评论 (0)编辑 收藏

Java中可以使用HttpURLConnection来请求WEB资源。
HttpURLConnection对象不能直接构造,需要通过 URL.openConnection()来获得HttpURLConnection对象,示例代码如下:
String urlStr= www.ttt.org;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();

 

HttpURLConnection是基于HTTP协议的,其底层通过socket通信实 现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时:
System.setProperty("sun.net.client.defaultConnectTimeout", 超时毫秒数字符串);
System.setProperty("sun.net.client.defaultReadTimeout", 超时毫秒数字符串);

其中: sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒)
sun.net.client.defaultReadTimeout: 从主机读取数据的超时时间(单位:毫秒)

例如:
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");

JDK 1.5以前的版本,只能通过设置这两个系统属性来控制网络超时。在1.5中,还可以使用HttpURLConnection的父类 URLConnection的以下两个方法:
setConnectTimeout:设置连接主机超时(单位:毫秒)
setReadTimeout: 设置从主机读取数据超时(单位:毫秒)

例如:
HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
urlCon.setConnectTimeout(30000);
urlCon.setReadTimeout(30000);

来源:http://www.xd-tech.com.cn/blog/article.asp?id=37

另外可参考java中处理http连接超时的方法

JDK中的URLConnection参数详解

linux下设置connect连接超时的方法

java socket 用法(一)

Linux,可以修改/proc/sys/net/ipv4/tcp_syn_retries的值,缺省是72,大约5分钟左右,改小点时间就短些

posted @ 2010-04-13 19:00 leekiang 阅读(1720) | 评论 (0)编辑 收藏

C10K问题探讨
http://www.kegel.com/c10k.html


Host Websites with nginx on CentOS 5

posted @ 2010-03-29 01:13 leekiang 阅读(262) | 评论 (0)编辑 收藏

http://baike.baidu.com/view/1077487.htm
http://subject.it168.com/article/articleview.aspx?id=672857

posted @ 2010-03-24 23:46 leekiang 阅读(413) | 评论 (0)编辑 收藏

五个广泛流传的对大龄程序员的误解
程序员,不止干到35岁
35岁前程序员要规划好的四件事,健康居首位
40岁以后的程序员还能做什么?
IT 外企那点儿事(6):管理路线和技术路线
IT外企那点儿事(5):像系统一样升级
Hacker传说之不能说的秘密(2)
程序员有哪些发展方向
软件天才与技术民工
如何成为一名Java自由开发人员
如何成为一名专家级的开发人员
工程师——中国最可悲的职业!
竞争篇,如何以弱击强
开发与研发(上)

posted @ 2010-03-22 02:05 leekiang 阅读(264) | 评论 (0)编辑 收藏

validates_inclusion_of用于确保对象的属性值在指定的集合中

http://hot88zh.javaeye.com/blog/512561

posted @ 2010-03-22 01:55 leekiang 阅读(221) | 评论 (0)编辑 收藏

双重危机

posted @ 2010-03-21 20:05 leekiang 阅读(220) | 评论 (0)编辑 收藏

仅列出标题
共54页: First 上一页 13 14 15 16 17 18 19 20 21 下一页 Last