1

I have implemented a server as shown below.the idea is to get is spew "GoodBye" messages to a client connected to it.My problem is that I have a while loop.and when it gets out of the while loop (When I press ^C) I want it to close the socket. How do I handle that situation.Finally doesn't do it.

import java.net.*;
import java.io.*;

public class GreetingServer extends Thread
{
   private ServerSocket serverSocket;

   public GreetingServer() throws IOException
   {
      serverSocket = new ServerSocket(5063);
      serverSocket.setSoTimeout(0);
   }

   public void run()
   {
      Socket server = null;
      try
      {
      server = serverSocket.accept();
      }
      catch(SocketTimeoutException s)
      {
          System.out.println("Socket timed out!");
      }
      catch(IOException e)
      {
          e.printStackTrace();
      }

      while(true)
      {
         try
         {
            System.out.println("Just connected to "
                                + server.getRemoteSocketAddress());

            DataOutputStream out = new DataOutputStream(server.getOutputStream());

            out.writeUTF("\nGoodbye!");
         }
     catch(SocketTimeoutException s)
         {
            System.out.println("Socket timed out!");
         }
     catch(IOException e)
         {
            e.printStackTrace();
         }
     finally
     {
        try
            {
               server.close();  
            }
        catch (IOException e)
            {
          e.printStackTrace();
            }
    }
      }

   }
   public static void main(String [] args)
   {
      try
      {
         Thread t = new GreetingServer();
         t.start();
      }
      catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
liv2hak
  • 14,472
  • 53
  • 157
  • 270

1 Answers1

5

You can attach a shutdown hook to the JVM which gets run whenever the JVM shuts down.

A Quick google will get you started.

Richard Sitze
  • 8,262
  • 3
  • 36
  • 48
VishalDevgire
  • 4,232
  • 10
  • 33
  • 59
  • You'll also find TCP sockets "live on" for a while -- you can't close them & instantly reopen on the same port. If you Google, you'll find the reasons for this. – Thomas W Jul 27 '13 at 09:10