使用cmd远程java控制台应用程序控制

时间:2011-10-21 09:57:18

标签: java cmd pipelining

我有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();
  }
}

RemoteController:

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

进入一个命令提示符,以便在它工作时进行测试。它有时是有效的,有时不是,任何建议如何使它每次都有效?

1 个答案:

答案 0 :(得分:0)

所有问题都是Sender和Reader程序以随机​​顺序连接到主程序,因此添加Thread.sleep(200)解决了我的问题,抱歉烦人。 PS:如果您使用java(和cmd)进行编程,请尝试一下,我认为非常有趣。