package com.dy.testServer.console;
|
|
import java.io.Console;
|
import java.io.PrintWriter;
|
|
public class CommandConsole {
|
|
private Console console ;
|
private PrintWriter prtWrt ;
|
private static final String myPassword = "123456" ;
|
private static final String commandPrefix1 = ">>" ;
|
private static final String commandPrefix2 = "$: " ;
|
private static String commandPrefix = commandPrefix1 + commandPrefix2 ;
|
|
|
public CommandConsole(Console console)throws Exception{
|
this.console = console ;
|
if(this.console == null){
|
throw new Exception("严重错误,java控制台对象为空!");
|
}
|
prtWrt = console.writer() ;
|
}
|
|
/**
|
* 初始,检查并输出一些信息
|
* @param args 参数
|
* @throws Exception 异常
|
*/
|
public void init(String[] args) throws Exception{
|
PrintWriter prtWrt = console.writer() ;
|
if(args != null && args.length > 0){
|
String str = "" ;
|
for(String s : args){
|
str += s ;
|
}
|
prtWrt.println("info:启动参数" + str);
|
}
|
|
prtWrt.println("----------------------------------------");
|
prtWrt.println("-- --");
|
prtWrt.println("-- 欢迎使用mwTest 服务控制端 --");
|
prtWrt.println("-- --");
|
prtWrt.println("----------------------------------------");
|
}
|
|
/**
|
* 执行控制台控制
|
* @return 返回
|
*/
|
public boolean clientConsole(){
|
boolean exit = false ;
|
try {
|
this.login() ;
|
exit = this.doConsole();
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return exit ;
|
}
|
|
private boolean login(){
|
while (true) {
|
//String username = console.readLine("Username: ");
|
char[] password = console.readPassword(">>Password: ");
|
String passwordStr = String.valueOf(password) ;
|
if (passwordStr.equals("help")) {
|
console.printf("密码是%1$s.\n", "123456");
|
// 使用后应立即将数组清空,以减少其在内存中占用的时间,增强安全性
|
password = null;
|
} else if(passwordStr.equals(myPassword)){
|
return true;
|
}
|
}
|
}
|
|
private boolean doConsole(){
|
boolean exit = false ;
|
while (!exit) {
|
String command = console.readLine(commandPrefix);
|
exit = Command.dealCommand(command, prtWrt) ;
|
}
|
return exit ;
|
}
|
|
public static void changeCommandPrefix(String prefix){
|
commandPrefix = commandPrefix1 + prefix ;
|
}
|
public static void recoverCommandPrefix(){
|
commandPrefix = commandPrefix1 + commandPrefix2 ;
|
}
|
}
|