[英]How to read response from Client-Server Socket Connection?
I am executing shell commands from my Android APP. 我正在从我的Android APP执行Shell命令。 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();
}
There is nothing wrong with my code. 我的代码没有错。 It was the server that was not sending any response.
是服务器未发送任何响应。
You have to set timeout for socket 您必须设置套接字超时
clientSocket .setSoTimeout(5000); clientSocket .setSoTimeout(5000); // milisekundy
// milisekundy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.