在Socket中处理多个客户端

时间:2012-04-07 05:51:17

标签: java multithreading sockets

我开发了一个java swing客户端 - 服务器应用程序。服务器有许多服务,如数据库服务,缓存服务和客户端服务会话。

客户端服务在端口上打开套接字并侦听传入连接。它为每个客户端连接生成一个新线程,创建一个会话并读取传入的序列化对象。它维护此会话(使线程保持活动状态),直到客户端发出'CLOSE_SESSION'命令。

我想知道的是,为每个新的客户端套接字会话生成一个新线程是否正确。感谢。

我的客户服务代码如下。

创建服务器套接字的代码:

            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));
            }

为每个客户端生成新线程的代码

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) {

    }

}

}

1 个答案:

答案 0 :(得分:3)

如果您的客户端会话请求可以持续很长时间,那么每个连接的线程是一个很好的解决方案。

替代方案是:

  • 使用NIO;
  • 如果客户端请求很短,请使用线程池。