简体   繁体   中英

How to keep the server socket alive after client abruptly disconnects?

The once the client disconnects and I restart the client, the server gives read line timeout. and when I run the server again, it works fine. So after disconnect one time I get read line timeout exception and next time it works.

import java.io.*;

public class TcpServer {

    ServerSocket welcomeSocket;

    public TcpServer() throws IOException{

        createSocket(port);
    }

    public TcpServer(int port) throws IOException{

        createSocket(port);
    }

    private void createSocket(int port) throws IOException{

        welcomeSocket = new ServerSocket(port);

    }

    @Override
    public void listen() throws IOException{

        boolean exitServer = false;
        Socket connectionSocket = null;

        try {
            while (!exitServer ) {
                    if(...){
                    exitServer = true;
                }
                }
            }
        } catch (IOException e) {

           try {
               welcomeSocket.accept();
               listen();
           } catch (IOException e1) {
               System.out.println("Cannot open connection!!!");
           }

        } 
    }
}

The ServerSocket.accept() method blocks and returns a new client socket connection when someone tries to connect. Put it in a while loop and then spawn a thread for this new socket worker. Something similar to this:

 ServerSocket welcomeSocket = new ServerSocket(port);
 while (true) {
     Socket socket = welcomeSocket.accept();
     new Thread(new RunnableSocketWorker(socket));
 }

If your client does decide to disconnect, that's fine, let them. You want the socket worker that was working on it to exit. If a new client tries to connect, they will do so above with your ServerSocket object and this infinite loop.

A big reason sockets are relatively easy in Java is that this ServerSocket class handles all incoming new clients. Why would you want to code that part yourself?

Just take the socket it returns and have fun!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM