Showing posts with label Network. Show all posts
Showing posts with label Network. Show all posts

Thursday, September 25, 2008

Testing server performance with multiple connection

Continues from previous post, this method is very useful to test the server performance with multiple request at the same time.

public void testMultiConnection(final String host, final int port,
final List messages, int noOfThread) {
// testing multiple request with different thread
for (int i = 0; i <>
final int threadNumber = i;
Thread connector = new Thread(new Runnable() {
@Override
public void run() {
for (String msg : messages) {
System.out.println("response from Thread["
+ threadNumber + "]:"
+ getResponse(host, port, msg));
}
}
});
connector.start();
}
}

Sending request message to server

public String getResponse(String host, int port, String requestString) {

Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
StringBuilder sb = new StringBuilder();
try {
socket = new Socket(host, port);
socket.setTcpNoDelay(true);
socket.setSoTimeout(6000);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));

out.println(requestString);
out.flush();
String line = null;
do {
line = in.readLine();
if (line != null) {
sb.append(line);
}
} while (line == null);

} catch (Exception e) {
// handle error during sending request
} finally {
if (out != null) {
out.close();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {

}
}
}
return sb.toString();
}

Wednesday, September 24, 2008

Creating Java Socket Server

public void startSocket(int port) {
//this is the request handler class
MessageHandler handler = new MessageHandler();
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
//handle error when socket is not available
}
while (true) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
//handle error when receiving request
}
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String request = getRequest(in);
//perform the request with handler
String result = handler.execute(request);
out.println(result);
} catch (SocketException ex) {
//handle error for process request
} catch (Exception e) {
//handle error for any kind of error
} finally {
try {
if (out != null)
out.flush();
out.close();
} catch (Exception ex) {
}
try {
in.close();
} catch (IOException e) {
}
try {
clientSocket.close();
} catch (Exception e) {
}
}//end of processing
}//end of one request processing
}