Search code examples
javaserversocket

How do i stop my server in java


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.


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().