Java 用于与服务器终端通信的套接字
我需要从服务器读取一些数据,我可以通过终端获取这些数据,现在我需要实现自动化。基本上我需要发送命令(红色)和读取响应(黄色) 据我所知,我可以使用套接字解决该任务。我已经实现了一个使用套接字的类(见下文) 连接工作良好Java 用于与服务器终端通信的套接字,java,sockets,Java,Sockets,我需要从服务器读取一些数据,我可以通过终端获取这些数据,现在我需要实现自动化。基本上我需要发送命令(红色)和读取响应(黄色) 据我所知,我可以使用套接字解决该任务。我已经实现了一个使用套接字的类(见下文) 连接工作良好 Socket clientSocket = new Socket(endpoint, port); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader i
Socket clientSocket = new Socket(endpoint, port);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
然后我发送这样的命令:
out.println(msg); // msg = "Gstatus\r\n"
之后,我希望BufferReader有一些数据要读取
int letter;
while(in.ready() && (letter = in.read()) != -1) {
char c = (char) letter;
res += c;
}
但是res总是空的
你能告诉我我做错了什么吗?或者纠正我的方向
谢谢。我用
DataInputStream
和DataOutputStream
这样做:
Server.java:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(10001);
Socket socket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
String command = (String) dataInputStream.readUTF();
StringBuilder commandLineResult = new StringBuilder();
Process process = Runtime.getRuntime().exec(command);
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
commandLineResult.append(line + "\n");
}
}
dataOutputStream.writeUTF(commandLineResult.toString());
serverSocket.close();
}
}
Client.java:
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket clientSocket = new Socket("localhost", 10001);
DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
dataOutputStream.writeUTF("ls -l");
System.out.println(dataInputStream.readUTF());
}
}
当服务器运行时,客户端可以使用其DataOutputStream
编写命令。之后,服务器可以使用该命令:
服务器使用
DataInputStream
从客户端套接字获取命令,然后将其传递到Runtime.getRuntime().exec(command)
方法。该方法有一个inputStream
,您可以稍后从process
读取并写入服务器的DataOutputStream
,后者将命令行内容发送到客户端套接字。之后,您可以使用需要运行servlet的客户机的数据输入流
读取结果-不幸的是,我不能这样做。