Introduction
So you have built a cool web site with code you wrote or downloaded from great
sites like CodeProject, the next thing you might want to do is testing it: Can
your code handle more than, say 10 concurrent users? Does it have a memory
leak that will eventually lead to crash if you don't reboot?
Using Java For Stress Testing
Here is a simple java program I wrote that can query a web site
continuously. If you want to simulate more than one user, just start as
many instances of this program as you need. The command line to run it is:
java XYWebTest the_web_page number_of_milliseconds
The second parameter, number_of_milliseconds, is used to determine a
random time interval to sleep/pause between two requests. For example, the
following command
java XYWebTest "http://www.yahoo.com/" 20000
will query the www.yahoo.com site continuously, sleeping a random amount of
time from 0 up to 20000 milliseconds between consecutive requests.
If you omit the second parameter, the default number 10000 will be
used. If you put the following commands in a batch file and save it in the
same directory as the class file, then you will be able to run multiple
instances of this program by double clicking the batch file:
set ClassPath=.
start java XYWebTest "www.somesite.com" 60000
start java XYWebTest "www.somesite.com" 60000
start java XYWebTest "www.somesite.com" 60000
start java XYWebTest "www.somesite.com" 60000
start java XYWebTest "www.somesite.com" 60000
The java code is simple. You can use or modify it freely. I don't
pretend to be an expert in this field, I am sure if you look around, you can
find some other code or tools that do exactly the same thing.
Disclaimer: You are supposed to test
only your own web site with this code. I am not responsible for anything
you do. By the way, the code won't work if you need to go through a proxy
server to access web sites outside your company firewall.
Please visit my home page
for my other articles and software tools. Thank you.
The Code
import java.net.*;
import java.io.*;
import java.util.*;
public class XYWebTest
{
public static void main (String[] args)
{
Random randomGen = new Random(new Date().getTime());
while(true)
{
try
{
Thread.currentThread().sleep(
randomGen.nextInt(args.length>1?
(new Integer(args[1]).intValue
()):10000));
if(args.length>0)
{
System.out.println(args[0]);
URLConnection urlConn =
new URL(args[0]).openConnection();
urlConn.setUseCaches(false);
InputStream in = urlConn.getInputStream();
byte buf[] = new byte[4096];
int nSize = in.read(buf);
while(nSize>=0)
{
System.out.print(new String(buf,0,nSize));
nSize = in.read(buf);
}
System.out.print("\r\n");
}
else return;
}
catch(Exception e)
{
System.out.println("Exception: "+e.getMessage());
}
}
}
}