3
votes

I have implemented a socket with a server and single client. The way it's structured currently, the server closes whenever the client closes. My intent is have the server run until manual shutdown instead.

Here's the server:

public static void main(String args[]) { ;

    try
    {
         ServerSocket socket= new ServerSocket(17);

         System.out.println("connect...");
         Socket s = socket.accept();
        System.out.println("Client Connected.");


        while (true)
            {

                work with server

            }

}
catch (IOException e)
    {
        e.getStackTrace();
     }

}

I've tried surrounding the entire try/catch loop with another while(true) loop, but it does nothing, the same issue persists. Any ideas on how to keep the server running?

2

2 Answers

6
votes

It looks like what's going to happen in your code there is that you connect to a client, infinitely loop over interactions with the client, then when someone disrupts the connections (closes clearning, or interrupts it rudly - e.g., unplug the network cable) you're going to get an IOException, sending you down to the catch clause which runs and then continues after that (and I'm guessing "after that" is the end of your main()?)...

So what you need to do is, from that point, loop back to the accept() call so that you can accept another, new client connection. For example, here's some pseudocode:

create server socket
while (1) {
    try {
        accept client connection
        set up your I/O streams

        while (1) {
            interact with client until connection closes
        }
    } catch (...) {
        handle errors
    }
} // loop back to the accept call here

Also, notice how the try-catch block in this case is situated so that errors will be caught and handled within the accept-loop. That way an error on a single client connection will send you back to accept() instead of terminating the server.

0
votes

Keep a single server socket outside of the loop -- the loop needs to start before accept(). Just put the ServerSocket creation into a separate try/catch block. Otherwise, you'll open a new socket that will try to listen on the same port, but only a single connection has been closed, not the serverSocket. A server socket can accept multiple client connections.

When that works, you probably want to start a new Thread on accept() to support multiple clients. Simplest way to do so is usually to add a "ClinentHandler" class that implements the Runnable interface. And in the client you probably want to put reading from the socket into a separate thread, too.

Is this homework / some kind of assignment?