2

我有 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

进入命令提示符以在其工作时进行测试。它有时有效,有时无效,有什么建议如何让它每次都有效吗?

4

1 回答 1

0

所有的问题是 Sender 和 Reader 程序以随机​​顺序连接到主程序,所以添加 Thread.sleep(200) 解决了我的问题,抱歉烦人。PS:如果你用java(和cmd)编程,试试吧,我觉得我真的很有趣。

于 2011-10-23T16:02:03.550 回答