Run java with two command windows--one for co…

2008-02-23 09:28:14来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

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

上一篇: Struts 中常见错误
下一篇: 初步了解osworkflow designer

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Base-Jsp-3-JSTL

下一篇:初步了解osworkflow designer