I have an java application using Socket TCP/IP and GUI. Server always listens connection and receives message from client. When server received message, it will show a swing form.
My trouble is when I click on close button, the application will stop although I set server socket ALWAYS listens connection (by put method serverSocket.accept() in loop while(true)).
How can I solve that problem ?
Here is my code on Server:
public class TCPServer {
ServerSocket server = null;
BufferedReader in;
PrintWriter out;
Socket client = null;
//open serverSocket
public void openServer() {
try {
server = new ServerSocket(1234);
} catch (Exception e) {
e.printStackTrace();
}
}
//accept connection and read data
public void listening() {
try {
while (true) {
client = server.accept();
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
//read data from stream
String s = in.readLine();
System.out.println("String receive: " + s);
new NewJFrame().setVisible(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void closeServer() {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (client != null) {
client.close();
}
if (server != null) {
server.close();
}
} catch (Exception e) {
}
}
public static void main(String arg[]) {
TCPServer server = new TCPServer();
server.openServer();
server.listening();
server.closeServer();
}
}
From Javadoc:
In the
NewJFrameclass, remove this:setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);This is making the whole application shutdown when the close button is hit!
Replace it by:
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);This way you are sure only the window is disposed, not the whole application