41 import java.io.IOException;
42 import java.net.InetSocketAddress;
43 import java.net.SocketAddress;
44 import java.net.StandardSocketOptions;
45 import java.nio.channels.*;
47 import java.util.concurrent.Executors;
48 import java.util.concurrent.TimeUnit;
55 private final List<Client>
connections = Collections.synchronizedList(
new ArrayList<Client>());
57 private final AsynchronousServerSocketChannel
listener;
66 channelGroup = AsynchronousChannelGroup.withFixedThreadPool(Runtime.getRuntime().availableProcessors(),
67 Executors.defaultThreadFactory());
88 listener.accept(
null,
new CompletionHandler<AsynchronousSocketChannel, Void>() {
90 public void completed(AsynchronousSocketChannel
result, Void attachment) {
97 public void failed(Throwable exc, Void attachment) {
107 public void shutdown() throws InterruptedException, IOException {
117 listener.setOption(StandardSocketOptions.SO_REUSEADDR,
true);
123 return AsynchronousServerSocketChannel.open(
channelGroup);
135 channel.setOption(StandardSocketOptions.TCP_NODELAY,
true);
136 }
catch (IOException e) {
154 if (clientConnection !=
client) {
155 clientConnection.writeMessageFrom(
client, message);
166 System.err.println(
"ChatServer [-port <port number>]");
170 public static void main(String[] args)
throws IOException {
172 if (args.length != 0 && args.length != 2) {
174 }
else if (args.length == 2) {
176 if (args[0].equals(
"-port")) {
177 port = Integer.parseInt(args[1]);
181 }
catch (NumberFormatException e) {
185 System.out.println(
"Running on port " +
port);