1

I have this whole code. My Application hangs up after the windows is force shutdown then cancel.

application running... >> windows force shutdown >> cancel >> back to windows (application HANGS Up)

Its a java bug. I want to exit my application before it hangs up or before the window is closing.

Thanks

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.Random;

public class ServerWindow implements ActionListener{

    private RemoteDataServer server;



    private Thread sThread; //server thread

    private static final int WINDOW_HEIGHT = 200;
    private static final int WINDOW_WIDTH = 350;

    private String ipAddress;

    private JFrame window = new JFrame("Remote Control for Android");

    private JLabel addressLabel = new JLabel("");
    private JLabel portLabel = new JLabel("Android Remote Control Port: ");
    private JTextArea[] buffers = new JTextArea[3];
    private JTextField portTxt = new JTextField(5);
    private JLabel serverMessages = new JLabel("Not Connected");

    private JButton connectButton = new JButton("Start Server");
    private JButton disconnectButton = new JButton("Stop Server");

    public boolean connected = false;

    public ServerWindow(){
        server = new RemoteDataServer();
        window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        connectButton.addActionListener(this);
        disconnectButton.addActionListener(this);

        Container c = window.getContentPane();
        c.setLayout(new FlowLayout());

        try{
            InetAddress ip = InetAddress.getLocalHost();
            ipAddress = ip.getHostAddress();
            addressLabel.setText("Android Remote Control Server IP Address: "+ipAddress);
        }
        catch(Exception e){addressLabel.setText("IP Address Could Not be Resolved");}

        int x;
        for(x = 0; x < 3; x++){
            buffers[x] = new JTextArea("", 1, 30);
            buffers[x].setEditable(false);
            buffers[x].setBackground(window.getBackground());
        }

        portTxt.setEditable(false);
        Random portRandom = new Random();
        for (int i = 0; i < 10; i++) {

          int port = portRandom.nextInt(4998) + 1;
          int portNum = 5000+port;
          String portString = Integer.toString(portNum);
          portTxt.setText(portString);
          }

        c.add(addressLabel);
        c.add(buffers[0]);
        c.add(portLabel);
        //portTxt.setText("5444");
        c.add(portTxt);
        c.add(buffers[1]);
        c.add(connectButton);
        c.add(disconnectButton);
        c.add(buffers[2]);
        c.add(serverMessages);

        window.setLocationRelativeTo(null);
        window.setVisible(true);
        window.setResizable(false);

    }


    public void actionPerformed(ActionEvent e){
        Object src = e.getSource();

        if(src instanceof JButton){
            if((JButton)src == connectButton){
                int port = Integer.parseInt(portTxt.getText());
                runServer(port);
            }

            else if((JButton)src == disconnectButton){
                closeServer();
            }
        }
    }

    public void runServer(int port){
        if(port <= 9999){
            server.setPort(port);
            sThread = new Thread(server);
            sThread.start();
        }
        else{
            serverMessages.setText("The port Number must be less than 10000");
        }
    }

    public void closeServer(){
        serverMessages.setText("Disconnected");
        server.shutdown();
        connectButton.setEnabled(true);
    }

    public static void main(String[] args){
        new ServerWindow();
    }


    public class RemoteDataServer implements Runnable{
        int PORT;
        private DatagramSocket server;
        private byte[] buf;
        private DatagramPacket dgp;

        private String message;
        private AutoBot bot;

        public RemoteDataServer(int port){
            PORT = port;
            buf = new byte[1000];
            dgp = new DatagramPacket(buf, buf.length);
            bot = new AutoBot();
            serverMessages.setText("Not Connected");
        }

        public RemoteDataServer(){
            buf = new byte[1000];
            dgp = new DatagramPacket(buf, buf.length);
            bot = new AutoBot();
            serverMessages.setText("Not Connected");
        }

        public String getIpAddress(){
            String returnStr;
            try{
                    InetAddress ip = InetAddress.getLocalHost();
                    returnStr = ip.getCanonicalHostName();
            }
            catch(Exception e){ returnStr = new String("Could Not be Resolve Ip Address");}
            return returnStr;
        }

        public void setPort(int port){
            PORT = port;
        }

        public void shutdown(){
            try{server.close();
                serverMessages.setText("Disconnected");}
            catch(Exception e){}
        }
        public void run(){
            try {



                InetAddress ip = InetAddress.getLocalHost(); 
                serverMessages.setText("Waiting for connection on " + ip.getCanonicalHostName());
                server = new DatagramSocket(PORT, ip);
                connected = true;
                connectButton.setEnabled(false);
            }
            catch(BindException e){ serverMessages.setText("Port "+PORT+" is already in use. Use a different Port"); }
            catch(Exception e){serverMessages.setText("Unable to connect");}

            while(connected){
                // get message from sender
                try{ server.receive(dgp);

                    // translate and use the message to automate the desktop
                    message = new String(dgp.getData(), 0, dgp.getLength());
                    if (message.equals("Connectivity")){
                        //send response to confirm connectivity
                        serverMessages.setText("Trying to Connect");
                        server.send(dgp); //echo the message back
                    }else if(message.equals("Connected")){
                        server.send(dgp); //echo the message back
                    }else if(message.equals("Close")){
                        serverMessages.setText("Controller has Disconnected. Trying to reconnect."); //echo the message back
                    }else{
                            serverMessages.setText("Android Phone Connected to ARD Server");
                            bot.handleMessage(message);}
                }catch(Exception e){
                    serverMessages.setText("Disconnected");
                    connected = false;}
            }

        }

    }
    }
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
hybrid_18
  • 67
  • 4
  • 11
  • Hmmm, I would think this has more to with the JVM, than with your code. Perhaps somebody could shed some light on what methods the JVM calls when it is told to shutdown. – thatidiotguy Nov 02 '12 at 17:59
  • What does "hangs up" mean? Could you clarify your post? – GraphicsMuncher Nov 02 '12 at 17:59
  • 2
    http://stackoverflow.com/questions/512555/detect-windows-logout-in-java – Kirill Kulakov Nov 02 '12 at 18:00
  • when the force close dialog appears , windows must hv closed java process before. thats why on cancel, the app gets hangup. maybe!! – Mukul Goel Nov 02 '12 at 18:01
  • my application freezes. Buttons cant be click even the exit,minimize and maximize but theres no "Not Responding" alert. It a bug I guess http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7071160 – hybrid_18 Nov 02 '12 at 18:04

2 Answers2

1

Without spending much time to review your code (to be honest) just from the complaint it strikes me it is the I/O thread for your socket.
You can not interrupt it and it remains hunging.
In your case you should force to close the output/input streams from a shutdown hook in your network code. Another option would be to try to make your threads daemons

Cratylus
  • 52,998
  • 69
  • 209
  • 339
  • could you give me some code please. Im a begginer on this. Thanks – hybrid_18 Nov 04 '12 at 13:15
  • @hybrid_18:Check the answer here to see if it helps you:http://stackoverflow.com/questions/12230629/java-how-do-i-catch-interruptedexception-on-a-thread-when-interupted-by-anothe/12230729#12230729 – Cratylus Nov 04 '12 at 13:25
0

This fixes it for me:

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run() {
        // your shutdown code

        // if you really want to be sure the program exits
        Runtime.getRuntime().halt(0);
    }
}, "shutdown hook thread"));
Peter Tseng
  • 13,613
  • 4
  • 67
  • 57