Question

How do i stop a server cause the ss.close() doesn't stop the server. I am using the following code :

    public class Server {
        ServerSocket ss;
        boolean listening;


        public void StartServer() {
            try {
                ServerSocket ss = new ServerSocket(7777);
                listening = true;
                JOptionPane.showMessageDialog(null, "Server started");
            } catch (IOException ioe) {
                JOptionPane.showMessageDialog(null, "Error: " + ioe);
            }


        while(listening) {
            try {
                new Session(ss.accept());
            } catch(IOException ioe) {
                JOptionPane.showMessageDialog(null, "Error: " + ioe);
            }
        }
    }

    public void StopServer() {
        try {
            ss.close();
        } catch (Exception e) {}
    }
  }

I call the StopServer method somewhere else. I have also tried to set listening to false. Where i call the StartServer method i placed a Message Dialog to see if it continues.

    private void btn_StartActionPerformed(java.awt.event.ActionEvent evt) {                                          
            lbl_Image2.setText("");
            lbl_Image2.setIcon(new ImageIcon("../../Project/Images/GreenButton.png"));
            lbl_Image2.setVisible(true);
            btn_Start.setEnabled(false);
            btn_Stop.setEnabled(true);
            SV.StartServer();
            JOptionPane.showMessageDialog(null, "Stopped");
    }

When I try to call the StopServer() the message dialog doesn't pop up.

Was it helpful?

Solution

Change ServerSocket ss = new ServerSocket(7777); to ss = new ServerSocket(7777);. The ss variable referenced in the StopServer() method is not the same one that is started in StartServer().

OTHER TIPS

If u want to give control of starting/stopping the server, you have to create GUI based server in threads. Because in StartServer method following while loop will not release its control called by the component (Start Button).

while(listening) {
        try {
            new Session(ss.accept());
        } catch(IOException ioe) {
            JOptionPane.showMessageDialog(null, "Error: " + ioe);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top