简体   繁体   中英

Handling multiple clients in Socket

I have developed a java swing client-server application. The server has many services like database service, cache service and client service talks to the clients.

The client service opens a socket on a port and listens to incoming connections. It spawns a new thread for every client connection, creates a session and reads the incoming serialized object. It maintains this session (keeps the thread alive) till the client issues a 'CLOSE_SESSION' command.

What i would like to know is if its correct to spawn a new thread for every new client-socket session. Thanks.

My client service code is as below.

Code to create server socket:

            try {
                ServerSocket socket = new ServerSocket(serverPort);
                Socket listener = socket.accept();

                Thread client = new Thread(new ClientHandler(listener));
                client.start();

            } catch (IOException ex) {
                log.error(new Throwable(ex));
            }

Code to spawn new thread for every client

class ClientHandler implements Runnable {

private static Logger log = Logger.getLogger(ClientHandler.class);

private Socket listener;

public ClientHandler(Socket listener) {
    this.listener = listener;
}

public void run() {
    try {
        ObjectInputStream inStream = new ObjectInputStream(
                listener.getInputStream());
        try {
            ServiceRequestResponse request = (ServiceRequestResponse) inStream
                    .readObject();
            if (request != null && request.getServiceCommand() != null) {

                ServiceCommand command = request.getServiceCommand();
                log.debug("command : " + command.getCommand());
                log.debug("is session alive? " + request.isAlive());
                log.debug("ServiceCommand.CREATE_SESSION : "
                        + ServiceCommand.CREATE_SESSION.getCommand());
                if (!request.isAlive()
                        && command.getCommand().equals(
                                ServiceCommand.CREATE_SESSION.getCommand())) {
                    // No session yet, and service command issued is login.
                    // Call login service, check credentials and create
                    // session.
                    request.setSessionId(UUID.randomUUID());
                    log.debug("Created user session with id : "
                            + request.getSessionId());
                } else {
                    if (command.getCommand().equals(
                            ServiceCommand.CLOSE_SESSION)) {
                        // Close session and do clean up here
                    }
                    // Here session is alive.
                    while (!ServiceCommand.CLOSE_SESSION.equals(command
                            .getCommand())) {
                        // Read the service command from the request
                        // response and
                        // Hand it over to the appropriate handler.
                    }

                }

            }

        } catch (ClassNotFoundException ex) {
            log.error(new Throwable(ex));
        }

    } catch (IOException ex) {

    }

}

}

If your client session request can last long then thread-per-connection is a good solution.

Alternatives are:

  • Using NIO;
  • Using thread pool if client requests are short.

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