if(server!= null){
try{
server.endServerConnection();
}
}
I thought closing the Server Socket would disconnect the Server. Am I missing something? Any ideas?
if(server!= null){
try{
server.endServerConnection();
}
}
I thought closing the Server Socket would disconnect the Server. Am I missing something? Any ideas?
Try closing the server socket any your socket...
public class MyServer {
public static final int PORT = 12345;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
Socket s = ss.accept();
Thread.sleep(5000);
ss.close();
s.close();
}
}
public class MyClient {
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
System.out.println(" connected: " + s.isConnected());
Thread.sleep(10000);
System.out.println(" connected: " + s.isConnected());
}
}
See content here...
My server runs on a separate thread, ServerThread class, to avoid the gui from freezing. I'm assuming I call ServerThread.sleep() in the server class. Also, my server class doesn't have a socket object (its on the client side to accept connections)
As far as I understand you, you have the ServerSocket object declared in the client class and call the ServerSocket:accept() method from there. This method is designed to "survive" any interruptions like closing the underlaying ServerSocket or calling interrupt() on the Thread that holds the socket.
The only way of exiting the ServerSocket:accept() method is a SocketTimeOutException, as mentioned in here.
So here is an example:
ServerSocket server = new ServerSocket(PORT);
server.setSoTimeOut(MILLISECONDS_TO_TIMEOUT);
while(YOUR_SERVER_SHOULD_RUN){
try{
Socket s = server.accept();
//Do stuff with the new socket
}catch(SocketTimeOutException ignored){}
}
The timeout will cause the ServerSocket to throw an exception when it's over. You can catch this exception and ignor it. The goal is to check the condition of the while loop.