I have a java program which consists of only an infinite while(true)
loop. I need to communicate with this program using sockets (or RMI,
or whatever is the right way to do it - please advise!).
I tried the standard socket syntax as below, but as you might guess,
the loop freezes while it waits for a command from the socket. I need
it to continue its loop w/ NO loss of performance if there is no
socket message sent to it.
Main program:
public static void main(String[] args) {
while (true) { // whole program is just infinite loop
ServerSocket serverSocket = null;
try { serverSocket = new ServerSocket(1234); }
catch (IOException e) {}
try {
Socket clientSocket = serverSocket.accept();
BufferedReader is = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintStream os = new PrintStream(clientSocket.getOutputStream());
String lineIn = is.readLine();
String response = processMsg(lineIn);
os.println(response);
os.flush();
}
catch (IOException e) {}
otherProcessing();
}
}
Communicator program:
public class Talk {
public static void main(String[] args) {
Socket socket = null;
InputStreamReader isr = null;
BufferedReader in = null;
PrintWriter out = null;
try {
socket = new Socket("localhost", 1234);
isr = new InputStreamReader(socket.getInputStream());
in = new BufferedReader(isr);
out = new PrintWriter(socket.getOutputStream(), true);
}
catch (Exception e) {}
if (socket!=null && isr!=null && in!=null && out!=null) {
try {
out.println(args[0]);
out.flush();
out.close();
in.close();
socket.close();
}
catch (Exception e) {}
}
}
So when this is complete, i will type 'java Talk command1',
and it will pass command1 on to the main program thru the socket/RMI.
And if there is no command sent from Talk, the main program will just
keep looping.
Please - if you answer this question, I expect the full completed
code, not just pointers to the solution. Thank you in advance, -t |