We try to use socket to implement this kind of imagination and succeed.
First, write a class to recieve and print message.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class ScreenPrinter {
private ServerSocket server;
private static Socket socket;
private static PrintWriter out;
private static int port=9998; // any free port
public ServerSocket getServer() {
return server;
}
public ScreenPrinter() throws Exception{
server=new ServerSocket(port);
}
public static void main(String[] args){
try{
if(args!=null){
if(args.length>0){
ScreenPrinter.port=Integer.parseInt(args[0]); //set port with args
}
}
ScreenPrinter printer=new ScreenPrinter();
System.out.println("socket opened [port]:"+port);
Socket incoming = printer.getServer().accept();
if(incoming.isConnected() && !incoming.isClosed()){
BufferedReader in=new BufferedReader(new InputStreamReader(incoming.getInputStream()));
while(true){
String str=in.readLine();
System.out.println(str);
}
in.close();
incoming.close();
}else{System.out.println("socket closed");}
}catch(Exception e){
e.printStackTrace();
try{
System.in.read();
}catch(Exception e2){
e2.printStackTrace();
}
}
}
// be invoked to print message
public static void printMessage(String msg){
try{
if(socket==null || out==null){
socket = new Socket(InetAddress.getLocalHost(),port);
out=new PrintWriter(socket.getOutputStream(),true);
System.out.println("Connected");
}
if(out!=null){
out.println(msg);
out.flush();
}
}
catch(Exception e){
e.printStackTrace();
}
}
Then another class to decide what to print
public class Messager{
public static void main(String[]args){
//open command window to display, can add port after class name
Runtime.getRuntime().exec("cmd.exe /c start java ScreenPrinter ");
//then you can use ScreenPrinter to print messages
ScreenPrinter. printMessage(“Ready");
}
You can make you program just like Messager, including any logic. ScreenPrinter is only a printer, recieving messages through the static method ScreenPrinter. printMessage(String).