如何在Java中创建基于命令的日志记录控制台

时间:2015-09-27 03:17:13

标签: java

所以我是一名自学成才的开发人员,输入和输出流是我最弱的一些主题。我想制作一个基于控制台的服务器程序,它将弹出自身与客户端之间发生的事件的输出日志,同时允许直接从控制台窗口输入命令(例如"停止"或&# 34;更新"或我要添加的任何其他命令)。我使用Scanner&System和System.out以及Console类本身的所有测试都没有产生任何结果,我无法在youtube,google或本网站上找到一些信息。有人可以帮帮我吗?我真的很感激,因为这是阻止我编写第一个完整程序的唯一因素。

主题1

public class Main {

public static volatile boolean running = true;

public static void main(String[] args) {
    Console console = System.console();
    MainThread mainThread = new MainThread();
    mainThread.start();
    System.out.println("Thread 1 Started");


    while(running){
        String s = console.readLine("%n>","%n" );
        if(s.equalsIgnoreCase("stop")){
            running = false;
            System.out.println("Bye!");
        } else {
            System.out.println("You said: " + s);
        }
    }
    System.out.println("Program Stopping...");
}

线程2

public class MainThread extends Thread {

private static final Logger log = Logger.getLogger(MainThread.class.getName());

public MainThread(){

}


@Override
public void run(){


    while(Main.running){
        log.info("Example Log Output");

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这里有一些服务器端代码可以给你一个想法:

final Socket client = serverSocket.accept(); //will set the client variable to whoever connects
final ObjectInputStream in = new ObjectInputStream(client.getInputStream()); //for getting client's input
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream()); //for sending objects to the client

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); //for reading in from server's console

String input;
while((input = stdIn.readLine()) != null) { //will read in from console
    out.writeObject(input); //will send console output to connected client
}
new Thread(new Runnable() {
    public void run() {
        Object objIn;
        while(!client.isClosed()) {
            if((objIn = in.readLine()) != null) {
                System.out.println("From client: " + objIn.toString());
            }
        }
    }
}).start();

以下是客户需要的代码:

Socket connection = new Socket(host, port); //connect to the server
ObjectOutputStream out = new ObjectOutputStream(connection.getOutputStream()); //for sending objects to the server
out.flush();
ObjectInputStream in = new ObjectInputStream(connection.getInputStream()); //for getting server's input

Object input;
while(!connection.isClosed()) { //will only cycle through if connection is open
    if((input = in.readObject()) != null) { //checks if we actually got an object
        System.out.println("Input from server: " + input.toString()); //print out server's console input
    }
}

它显然没有完全按照您的代码完成,因此需要进行调整。但要点是有效的。