创建基于命令的记录器程序



>我目前正在尝试制作一个创建和写入日志文件的Java程序。

它有 2 个类(一个用于请求,一个用于工作线程代码)。 一个类有一个文本字段,允许您输入命令。 命令应该类似于"日志启动"或"日志停止"。

因此,请求类将命令作为字符串发送,worker 类获取命令,解析它并执行指令(开始日志记录,停止日志记录。

我的问题是:当用户输入"停止"命令时,应用程序不会停止日志记录。 好吧,它在 3 个日志条目后不会停止(这就是问题所在。 我想在用户输入命令时随时停止它) 当您查看代码时,您会更好地理解问题。

我知道我在这里犯了一个非常基本的错误,但不知何故目前无法弄清楚,并希望您对这个问题发表意见。(我展示了代码中的问题)谢谢。

错误:

Exception in thread "stoplogging" java.lang.ArrayIndexOutOfBoundsException: 1
    at Response$ClientProcess$1StopperThread.run(Response.java:109)
    at java.lang.Thread.run(Unknown Source)

请求类:

public class Request extends JFrame {
private JTextArea consoleArea = new JTextArea();
private JTextField cmd_prompt = new JTextField();
private JLabel cmd_label = new JLabel("Enter command: ");
// ********IP PORT TEXTFIELDS & CONNECT BUTTON*******  !!!!
private DataOutputStream output; 
private DataInputStream input;

public static void main(String[] args) {
    new Request();
}
Socket socket = null;
String command;
public Request (){
    JPanel requestPanel = new JPanel();
    requestPanel.setLayout(new BorderLayout());
    setTitle("Project_3002_CLIENT");
    requestPanel.add(cmd_label, BorderLayout.WEST);
    requestPanel.add(cmd_prompt, BorderLayout.CENTER);
    setLayout(new BorderLayout());
    add(requestPanel, BorderLayout.NORTH);

    add(new JScrollPane(consoleArea), BorderLayout.CENTER);
    Font font = new Font("Courier New", Font.BOLD, 15);
    cmd_prompt.setFont(font);
    cmd_prompt.setAlignmentX(LEFT_ALIGNMENT);
    cmd_prompt.addActionListener(new TextFieldListener());
    setSize(600, 270);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    consoleArea.setFont(font);
    setVisible(true);
    String ip = "127.0.0.1"; // THIS WILL BE CHANGED (make custom) --extra jframe
    int port = 4588; // THIS WILL BE CHANGED (make custom) -- extra jframe
    try {
        socket = new Socket(ip, port);
        //IO connection stuff
        input = new DataInputStream(socket.getInputStream());
        output = new DataOutputStream(socket.getOutputStream());
    }
    catch (IOException ex) {
        consoleArea.append("Connection refused. Please check if the server is running.n");
    }
}
class SenderThirty implements Runnable{
    Thread send30secs;
    public SenderThirty(){
    }
    public SenderThirty(String send30s){
        send30secs = new Thread(this, send30s);
        send30secs.start();
    }
    @Override
    public void run() {
        try {
            output.writeUTF(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
private class TextFieldListener implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        try {
            command = cmd_prompt.getText();
            if (command.contains("start") == true){
                Thread sendstart = new Thread(new SenderThirty(), "send");
                sendstart.start();
                //continue
            }
            else if (command.contains("stop") == true){
                Thread sendstop = new Thread(new SenderThirty(), "send");
                sendstop.start();
                //continue
            }
            else {consoleArea.append("nInvalid commandn");}

        } catch (Exception e1) {
            consoleArea.append("nERR!n");
        }
    }
}}

工人类:

public class Response {
String path = "";
public static void main(String[] args) throws InterruptedException {
    new Response();
}
ServerSocket resp_sock;
public Response() throws InterruptedException {
    int port = 4588;
    try {
        resp_sock = new ServerSocket(port);
        int clientNo = 1;
        while (true) {
            Socket socket = resp_sock.accept();

            // client's IP address
            InetAddress client_addr = socket.getInetAddress();
            ClientProcess task = new ClientProcess(socket);
            new Thread(task).start();
            clientNo++;
        }
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, ex);
    }
}
class ClientProcess implements Runnable {
    private Socket socket; 
    public ClientProcess(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            final DataInputStream input = new DataInputStream(socket.getInputStream());//from client
            //DataOutputStream output = new DataOutputStream(socket.getOutputStream());//to client
            while(true){
                String prompt = input.readUTF();
                String command[] = prompt.split(" ");
                final Logger logger = Logger.getLogger("MyLog"); 
                FileHandler fh;             
                fh = new FileHandler("C:\..path..\logfile.log");  
                logger.addHandler(fh);                      
                SimpleFormatter formatter = new SimpleFormatter();  
                fh.setFormatter(formatter);


                class StopperThread implements Runnable{
                    public StopperThread(){
                    }           
                    @Override
                    public void run() { 
                        try { ////////////////////////////////////////***PROBLEM IS IN THIS TRY BLOCK***
                            String next_prompt;
                            next_prompt = input.readUTF();
                            String nextCommand[] = next_prompt.split(" ");
                            if(nextCommand[1].equalsIgnoreCase("stop")){
                                logger.info("STOPPED   " + new Date() + "  n");
                                System.exit(0);}
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }}



                if(command[1].equalsIgnoreCase("start")){
                    try {
                        while(true){
                            logger.info("RUNNING   " + new Date() + "  n");
                            Thread.sleep(5000);
                            Thread stoplogging = new Thread(new StopperThread(), "stoplogging");
                            stoplogging.start();
                        }
                    } catch (SecurityException e) {  
                        e.printStackTrace();  
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }  
                }

                if(command[1].equalsIgnoreCase("stop")){
                    logger.info("STOPPED   " + new Date() + "  n");  
                }

            }
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
    }
}}
if(nextCommand[1].equals...)很可能

是罪魁祸首。

如果您拆分的字符串中没有空格 (" "),它将抛出 NPE,在这种情况下,nextCommand 的长度将为 1,而不是 2。

您应该事先检查长度。注意:与 command[1] 相同的潜在错误。

最新更新