【发布时间】:2015-03-13 13:59:26
【问题描述】:
我有一个 android 应用程序连接到我的 linux 服务器(它具有侦听连接的 java 端口侦听器),当我发送命令(例如“uname”)时,它会在终端端输出“linux”(其中是故意的,因为它只是临时的,以确保它的可读性)并且当我将它发送回来(假设它接收到)时,android 没有收到它,或者 java 从不发送它开始,这里是客户端(android)通讯代码。
public void onClick(View v) {
try{
OutputStream outStream = socket.getOutputStream();
String message = "uname";
outStream.write(message.getBytes());
while(true){
DataInputStream dis = new DataInputStream(socket.getInputStream());
byte[] disbyte = new byte[1024];
dis.read(disbyte);
String disString = new String(disbyte);
//temporarily text place holder when server sends output back.
serveresponse.setText(disString);
}
}catch(Exception e){
}
}
这是服务器端(Linux机器上的Java)通信代码
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Listening on Port: "+PORT);
Socket clientSocket = serverSocket.accept();
System.out.println("New Client has connected");
while(listening){
DataInputStream input = new DataInputStream(clientSocket.getInputStream());
byte[] bread = new byte[1024];
input.read(bread);
String instring = new String(bread);
try {
shellprocess = Runtime.getRuntime().exec(instring);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(shellprocess.getInputStream()));
String s = null;
while((s = stdInput.readLine()) != null){
OutputStream outStream = clientSocket.getOutputStream();
outStream.write(s.getBytes());
outStream.flush();
//this line is to see if the output is correct in the terminal, just here temporarily
System.out.println(s);
}
}catch(Exception e){
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我的问题是如何将响应(shell 命令的输出)发送回 android 客户端?
【问题讨论】:
-
你调试了吗?只是因为我很好奇,你为什么使用套接字而不是抽象出来的库? javaworld.com/article/2077322/core-java/…
-
很抱歉,因为工作迟到和周五迟到了。我使用了套接字,因为我认为应该使用套接字。
-
您的问题解决了吗?好吧,如果您想了解如何使用它们,是的,它们是一个很好的起点,但是如果您想快速开发一个应用程序,请寻找可以帮助您的库,因为您必须注意很多事情的。对于 Android,您可以查看 OKHttp 或 Spring Rest 模板。在服务器端,spring data rest 可能是有效编写服务的不错选择。