Мой текущий подход:
Код: Выделить всё
final Semaphore wait = new Semaphore(1);
while(true){
wait.acquire();
this.asyncSocket.accept(null, new CompletionHandler() {
@Override
public void completed(AsynchronousSocketChannel result, Void attachment) {
wait.release();
asyncSocket.accept(null, this);
...
}
...
}
}
Другой подход:
Код: Выделить всё
final Semaphore wait = new Semaphore(1);
while(true){
wait.acquire();
final Future futureChannel = this.asyncSocket.accept();
this.exec.execute(new Runnable() {
@Override
public void run() {
try (final AsynchronousSocketChannel clientChannel = futureChannel.get()) {
wait.release();
try (ObjectInputStream ois = new ObjectInputStream(Channels.newInputStream(clientChannel))) {
final Command cmd = (Command) ois.readObject();
cmd.execute(util, clientChannel, null, logger).run();
}
} catch (IOException | InterruptedException | ClassNotFoundException | ExecutionException e) {
e.printStackTrace();
}
}
});
К сожалению, в обеих реализациях сервер оставляет много открытых сокетов в состоянии TIME_WAIT, хотя я закрываю их и на сервере, и на стороне клиента..
Итак, на самом деле у меня есть 2 вопроса:
- Как правильно использовать AsynchronousServerSocketChannel для реализации Сервера, который принимает больше соединений.
- Как избавиться от открытых сокетов в состоянии TIME_WAIT
Код: Выделить всё
private T sendCommand(final Command command) throws ExecutionException, InterruptedException, IOException, ClassNotFoundException {
T result = null;
try (final AsynchronousSocketChannel channel = AsynchronousSocketChannel.open(channelGroup)) {
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.connect(this.mwInfo.getNextMiddleware()).get();
final OutputStream os = Channels.newOutputStream(channel);
final InputStream is = Channels.newInputStream(channel);
try (final ObjectOutputStream oos = new ObjectOutputStream(os)) {
oos.writeObject(command);
oos.flush();
try (final ObjectInputStream ois = new ObjectInputStream(is)) {
result = (T) ois.readObject();
}
}
}
return result;
}
Подробнее здесь: https://stackoverflow.com/questions/330 ... ketchannel
Мобильная версия