服务端
package cn;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
public class ChatServer {
public static void main(String[] args) throws IOException {
start();
}
public static void start() throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("[服务启动]");
while (true) {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (key.isAcceptable()) {
connect(serverSocketChannel, selector);
}
if (key.isReadable()) {
read(key, selector);
}
}
}
}
private static void connect(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException {
SocketChannel accept = serverSocketChannel.accept();
accept.configureBlocking(false);
accept.register(selector, SelectionKey.OP_READ);
System.out.println("["+accept.keyFor(selector)+" 上线]");
accept.write(ByteBuffer.wrap("[欢迎进入聊天室]".getBytes()));
}
private static void read(SelectionKey key, Selector selector) {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int len = 0;
try {
len = socketChannel.read(byteBuffer);
} catch (IOException e) {
key.cancel();
e.printStackTrace();
System.out.println("["+key.toString()+" 下线]");
return;
}
if (len > 0) {
String msg = new String(byteBuffer.array(), 0, len);
msg="["+key.toString()+"]:"+msg;
System.out.println(msg);
broadcast(msg, key, selector);
}
}
private static void broadcast(String msg, SelectionKey msgKey, Selector selector) {
selector.keys().forEach(key -> {
ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
if (key.channel() instanceof SocketChannel && !msgKey.equals(key)) {
SocketChannel targetChannel = (SocketChannel) key.channel();
try {
targetChannel.write(byteBuffer);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
客户端
package cn;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.PrimitiveIterator;
import java.util.Scanner;
import java.util.Set;
public class ChatClient {
private static Selector selector;
private static SocketChannel channel;
public static void main(String[] args) throws IOException {
start();
}
public static void start() throws IOException {
init();
new Thread(ChatClient::read).start();
new Thread(ChatClient::write).start();
}
private static void init() throws IOException {
channel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
channel.configureBlocking(false);
selector = Selector.open();
channel.register(selector, SelectionKey.OP_READ);
}
private static void write() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String msg = scanner.nextLine();
try {
if ("quit".equals(msg)) {
System.exit(0);
}
channel.write(ByteBuffer.wrap(msg.getBytes()));
} catch (IOException e) {
System.out.println("[服务器下线]");
System.exit(0);
e.printStackTrace();
}
}
}
private static void read() {
while (true) {
try {
selector.select();
} catch (IOException e) {
e.printStackTrace();
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (key.isReadable()) {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int len = 0;
try {
len = socketChannel.read(byteBuffer);
} catch (IOException e) {
key.cancel();
e.printStackTrace();
System.exit(0);
}
if (len > 0) {
System.out.println(new String(byteBuffer.array(), 0, len));
}
}
}
}
}
}