私はJavaSwingクライアントサーバーアプリケーションを開発しました。サーバーには、データベースサービス、キャッシュサービス、クライアントとのクライアントサービス通信などの多くのサービスがあります。
クライアントサービスは、ポートでソケットを開き、着信接続をリッスンします。クライアント接続ごとに新しいスレッドを生成し、セッションを作成して、着信するシリアル化されたオブジェクトを読み取ります。クライアントが「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) {
}
}
}