Run java with two command windows--one for control, another for display information

王朝java/jsp·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

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).

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航