0

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.

MeNa
  • 1,481
  • 9
  • 22
Kobus
  • 25
  • 1
  • 5
  • Inside StartServer() you shouldn't be doing this: ServerSocket ss = new ServerSocket(7777); because you defined ServerSocket as a field already. So it should be ss = new ServerSocket(7777). – Omoro Feb 04 '14 at 12:26
  • Doesn't this code throw NPE on each run? – Xabster Feb 04 '14 at 12:26
  • @Xabster No it doesn't throw a NPE. Thanks just had to change the ServerSocket ss = new ServerSocket(7777); to ss = new ServerSocket(7777); – Kobus Feb 04 '14 at 13:34

2 Answers2

4

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

Petter
  • 3,843
  • 23
  • 31
0

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);
        }
    }
Sarz
  • 1,951
  • 3
  • 20
  • 41