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

时间:2012-07-07 07:00:37

标签: java multithreading sockets logging indexoutofboundsexception

我正在尝试创建一个创建和写入日志文件的java程序。

它有2个类(一个用于请求,一个用于工作代码)。一个类有一个文本字段,允许您输入命令。命令应该像'log start'或'log stop'。

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

我的问题是:当用户输入'stop'命令时,应用程序不会停止记录。好吧,它不会在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 command\n");}


        } 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);
        }
    }

}}

1 个答案:

答案 0 :(得分:0)

if(nextCommand[1].equals...)很可能是罪魁祸首。

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

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