나는 자바 스윙 클라이언트 - 서버 응용 프로그램을 개발했습니다. 서버는 데이터베이스 서비스, 캐시 서비스 및 클라이언트 서비스와 같은 많은 서비스를 클라이언트에 제공합니다.소켓에서 여러 클라이언트 처리
클라이언트 서비스는 포트에서 소켓을 열고 들어오는 연결을 수신합니다. 모든 클라이언트 연결에 대해 새 스레드를 생성하고 세션을 생성하며 들어오는 일련 화 된 객체를 읽습니다. 클라이언트가 '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) {
}
}
}
또한 (a) 해당 루프의 맨 아래에 EOFException을 잡아야합니다. (b) 다른 IOException을 기록하십시오. (c) finally {} 블록에서 소켓을 닫는다. – EJP