Domanda

I have Java console app, which i want to control from another computer. I use Socket class to send data through net and pipeline to connect the remote controlled program with Sender and Reader program, as shown:

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

Sender:

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

now i run the Remote controller and then i write

java Sender localhost 1234 | java SomeProgram | java Reader localhost 1234

into a comand prompt to test whenever it works. It sometimes works, sometimes not, any advise how to make it work everytime?

È stato utile?

Soluzione

All the problem was that the Sender and Reader programms conected in a random order to the main program, so adding Thread.sleep(200) resolved my problem, sorry for annoying. PS: If you program in java (and cmd), try it, iť really fun i think.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top