【发布时间】:2014-04-27 13:27:55
【问题描述】:
我正在制作一个程序,你在客户端输入 ifconfig(Linux) 或 ipconfig(Windows),然后它发送到服务器并在那里执行 shell。
运行正常,在服务端可以正确看到ipconfig,但是不知道如何将服务端的结果返回给客户端。
客户端:
public class ShellClient {
public static void main(String[] args) throws IOException {
String comand;
Socket server =null;
server = new Socket("localhost", 1234);
while(true){
System.out.println("Insert ipconfig(windows)/ ifconfig(Linux): ");
@SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
comando = keyboard.next();
try{
System.out.println("Conecting...");
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(server.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(server.getInputStream()));
out.writeUTF(comand);
out.flush();
String result = in.readUTF();
System.out.println(result);
if (comand == "0"){server.close();
System.out.println("Finish. Thank You!");
System.exit(0);}
}catch(IOException ioe){
System.err.println(ioe);
}
}
}
}
服务器端:
public class ShellServer {
public static void main(String[] args) throws IOException {
ServerSocket socket = null;
Socket client = null;
String result;
String comand ;
String s = null;
socket = new ServerSocket(1234);
System.out.println("The server keep working...");
client = socket.accept();
System.out.println("The client is connected");
DataInputStream in = new DataInputStream(new BufferedInputStream(client.getInputStream()));
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
comand = in.readUTF();
result = Shell.CheckCommand(comand);
//out.writeUTF(result);
//out.flush();
// Ejcutamos el comando
Process p = Runtime.getRuntime().exec(result);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
if(comand == "0"){client.close();
socket.close();}
}
}
提前谢谢你们!
【问题讨论】:
-
@drkunibar 谢谢你的链接,但是没有威胁就没有办法吗?
-
只是不要在服务器中创建任何线程并在服务器端处理(一次只有一个客户端)。
-
@Benjamin 但是我的代码有什么问题?