public class NIOServer {
public static void main(String[] args) throws IOException {
ServerSocketChannel listener = null;
System.out.println("服务器已启动...");
try {
listener = ServerSocketChannel.open();
listener.bind(new InetSocketAddress("10.9.63.249",5555));
listener.configureBlocking(false);
Selector selector = Selector.open();
listener.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select() > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
while (it.hasNext()) {
SelectionKey selectionKey = it.next();
if (selectionKey.isAcceptable()) {
SocketChannel socketChannel = listener.accept();
System.out.println(socketChannel.getRemoteAddress()+"进入了聊天室");
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
}else if (selectionKey.isReadable()) {
SocketChannel sChannel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int len = 0;
try {
while ((len = sChannel.read(buffer)) > 0) {
buffer.flip();
System.out.println(sChannel.getRemoteAddress() +"说了:"+new String(buffer.array(), 0, buffer.limit()));
buffer.clear();
}
if (len == -1) {
sChannel.close();
}
} catch (IOException e) {
System.out.println(sChannel.getRemoteAddress()+"异常退出了!");
sChannel.close();
}
}
}
it.remove();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
listener.close();
}
}
}
public class NIOClient {
public static void main(String[] args) throws Exception {
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("10.9.63.249", 5555));
socketChannel.configureBlocking(false);
Scanner scanner = new Scanner(System.in);
while (true) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
String data = scanner.nextLine();
buffer.put(data.getBytes());
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
if (data.equals("886")) {
break;
}
}
socketChannel.close();
}
}