Thursday, September 25, 2008

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();
}

No comments: