我有Java控制台应用程序,我想从另一台计算机控制。我使用Socket类通过网络和管道发送数据,将远程控制程序与Sender和Reader程序连接起来,如下所示:
读者:import java.io.*;
import java.net.*;
public class Reader {
//reads information from the remote controlled program
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], Integer.parseInt(args[1]));
PrintWriter bw = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String vstup;
do {
vstup = in.readLine();
if(vstup==null) break;
bw.println(vstup);
} while(true);
s.close();
}
}
发送者:import java.io.*;
import java.net.*;
public class Sender {
//sends instruction to the remote controlled program
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], Integer.parseInt(args[1]));
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String vstup;
do {
vstup = in.readLine();
if(vstup==null) break;
System.out.println(vstup);
} while(true);
s.close();
}
}
远程控制:
import java.net.*;
import java.io.*;
public class RemoteController {
public static void main(String[] main) throws IOException {
ServerSocket ss = new ServerSocket(Integer.parseInt(main[0]));
System.out.println("Done, please connect the program.");
Socket reader = ss.accept(); //reads what the program says
System.out.println("reader connected");
Socket writer = ss.accept(); //writes into the program
System.out.println("writer connected");
BufferedReader read = new BufferedReader(new InputStreamReader(reader.getInputStream()));
PrintWriter write = new PrintWriter(writer.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i<5; i++) {
write.println(br.readLine());
System.out.println(read.readLine());
}
write.close();
read.close();
writer.close();
reader.close();
ss.close();
}
}
现在我运行远程控制器,然后我写
java Sender localhost 1234 | java SomeProgram | java Reader localhost 1234
将放入命令提示符中以测试它是否有效。有时有效,有时无效,有什么建议让它每次都有效吗?
所有的问题是发送者和读者程序以随机顺序连接到主程序,所以添加Thread.sleep(200)解决了我的问题,抱歉打扰。PS:如果你用java(和cmd)编程,试试吧,我觉得真的很有趣。