Run java with two command windows--one for co…
2008-02-23 09:28:14来源:互联网 阅读 ()
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 printpublic class Messager{public static void main(String[]args){//open command window to display, can add port after class nameRuntime.getRuntime().exec("cmd.exe /c start java ScreenPrinter ");//then you can use ScreenPrinter to print messagesScreenPrinter. 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
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash