Reputation: 105
I am executing shell commands from my Android APP. I am able to execute the command but unable to read the response from Server. My code is as follows :
public String executeThroughSocket(int portNo, String portAddress, String command) throws IOException {
StringBuilder responseString = new StringBuilder();
PrintWriter writer = null;
BufferedReader bufferedReader = null;
Socket clientSocket = null;
try {
clientSocket = new Socket(portAddress, portNo);
if (!clientSocket.isConnected())
throw new SocketException("Could not connect to Socket");
clientSocket.setKeepAlive(true);
writer = new PrintWriter(clientSocket.getOutputStream(), true);
writer.println(command);
writer.flush();
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String str;
while ((str = bufferedReader.readLine()) != null) {
responseString.append(str);
}
} finally {
if (writer != null)
writer.close();
if (bufferedReader != null)
bufferedReader.close();
if (clientSocket != null)
clientSocket.close();
}
return responseString.toString();
}
Upvotes: 1
Views: 8221
Reputation: 9
You have to set timeout for socket
clientSocket .setSoTimeout(5000); // milisekundy
Upvotes: 0
Reputation: 105
There is nothing wrong with my code. It was the server that was not sending any response.
Upvotes: 2