目标:实现一个多人在线群聊系统
服务端
package com.it.chat;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
public class Server {
private Selector selector;
private ServerSocketChannel serverSocketChannel;
private Integer port;
public Server() throws Exception {
port = 8080;
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(new InetSocketAddress(port));
selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void handleEvent() throws Exception {
while (selector.select() > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
while (selectionKeyIterator.hasNext()) {
SelectionKey selectionKey = selectionKeyIterator.next();
if (selectionKey.isAcceptable()) {
handleAcceptEvent();
} else if (selectionKey.isReadable()) {
handleBroadCast(selectionKey.channel());
}
selectionKeyIterator.remove();
}
}
}
public void handleAcceptEvent() throws Exception {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
}
public void handleBroadCast(Channel channel) throws Exception {
SocketChannel originChannel = (SocketChannel) channel;
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int read = originChannel.read(byteBuffer);
String remoteAddress = originChannel.getRemoteAddress().toString().substring(1);
System.out.println(remoteAddress + " say: " + new String(byteBuffer.array(), 0, read));
byteBuffer.flip();
Set<SelectionKey> selectionKeys = selector.keys();
for (SelectionKey selectionKey : selectionKeys) {
Channel targetChannel = selectionKey.channel();
if (targetChannel instanceof SocketChannel && originChannel != targetChannel) {
SocketChannel destinationChannel = (SocketChannel) targetChannel;
destinationChannel.write(byteBuffer);
}
}
byteBuffer.clear();
}
public static void main(String[] args) throws Exception {
Server server = new Server();
server.handleEvent();
}
}
客户端
package com.it.chat;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Client {
private Selector selector;
private SocketChannel socketChannel;
private String host;
private Integer port;
private String username;
public Client() throws Exception {
host = "127.0.0.1";
port = 8080;
socketChannel = SocketChannel.open(new InetSocketAddress(host, port));
socketChannel.configureBlocking(false);
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_READ);
username = socketChannel.getRemoteAddress().toString().substring(1);
}
public void sendMessage(String message) throws Exception {
socketChannel.write(ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)));
}
public void acceptMessage() throws Exception {
while (selector.select() > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
while (selectionKeyIterator.hasNext()) {
SelectionKey selectionKey = selectionKeyIterator.next();
if (selectionKey.isReadable()) {
SocketChannel channel = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int length;
while ((length = channel.read(byteBuffer)) > 0) {
byteBuffer.flip();
System.out.println("【acceptMessage】" + username + " say:" + new String(byteBuffer.array(), 0, length));
byteBuffer.clear();
}
}
selectionKeyIterator.remove();
}
}
}
public static void main(String[] args) throws Exception {
Client client = new Client();
new Thread(() -> {
while (true) {
try {
client.acceptMessage();
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
client.sendMessage(scanner.nextLine());
}
}
}