目录
网络编程应用实例-群聊系统
服务器端
客户端
测试
网络编程应用实例-群聊系统
实例要求:
- 编写一个 NIO 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)实现多人群聊
- 服务器端:可以监测用户上线,离线,并实现消息转发功能
- 客户端:通过channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)
- 目的:进一步理解NIO非阻塞网络编程机制
服务器端
/**
* 群聊服务器端
*/
public class ChatGroupServer {
// 定义属性
private static Selector selector;
private ServerSocketChannel listenChannel;
private static final int PORT = 6666;
// 构造器,初始化
public ChatGroupServer() {
try {
// 得到选择器
selector = Selector.open();
// ServerSocketChannel
listenChannel = ServerSocketChannel.open();
// 绑定端口
listenChannel.socket().bind(new InetSocketAddress(PORT));
// 设置非阻塞模式
listenChannel.configureBlocking(false);
// 将listenChannel 注册到 selector
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
// 监听
private void listen() {
System.out.println("监听线程:" + Thread.currentThread().getName());
try {
// 循环处理
while (true) {
int count = selector.select();
if (count > 0) {
// 有事件需要处理
// 遍历得到 selectorKey 集合
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
// 取出 SelectorKey
SelectionKey key = iterator.next();
// 监听到accept
if (key.isAcceptable()) {
SocketChannel socketChannel = listenChannel.accept();
socketChannel.configureBlocking(false);
// 将 socket 注册到 selector
socketChannel.register(selector, SelectionKey.OP_READ);
// 上线提示
System.out.println(socketChannel.getRemoteAddress() + "--> 已上线...");
}
if (key.isReadable()) { // 通道发送read事件,即通道是可读的状态
// 处理读
readData(key);
}
// 当前的key删除,防止重复处理
iterator.remove();
}
} else {
System.out.println("等待...");
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
// 读取客户端消息
private void readData(SelectionKey key) {
// 取到关联的channel
SocketChannel socketChannel = null;
try {
// 得到channel
socketChannel = (SocketChannel) key.channel();
// 创建Buffer
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int read = socketChannel.read(byteBuffer);
// 根据 count 的值处理
if (read > 0) {
// 把缓存区的数据转换成字符串
String msg = new String(byteBuffer.array());
System.out.println("from 客户端:" + msg);
// 向其他的客户端发送消息(除去自己),
sendMsgToOtherClients(msg, socketChannel);
}
} catch (IOException exception) {
try {
System.out.println(socketChannel.getRemoteAddress().toString()+" 已下线...");
key.cancel();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 发送消息给其他客户(通道)
private void sendMsgToOtherClients(String msg, SocketChannel self) throws IOException {
System.out.println("服务器转发消息中...");
System.out.println("服务器转发消息给客户端线程:" + Thread.currentThread().getName());
// 遍历所有注册到Selector上的 SocketChannel,并排除self
for (SelectionKey key : selector.keys()) {
// 通过Key 取出 对应的SocketChannel
SelectableChannel targetChannel = key.channel();
// 排除自己
if (targetChannel instanceof SocketChannel && targetChannel != self) {
// 转型
SocketChannel dest = (SocketChannel) targetChannel;
// 将msg 存储到 Buffer
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
// 将Buffer 数据写入通道
dest.write(buffer);
}
}
}
public static void main(String[] args) throws IOException {
// 创建服务器对象
ChatGroupServer chatGroupServer = new ChatGroupServer();
// 监听
chatGroupServer.listen();
}
}
客户端
/**
* 群聊 客户端
*/
public class ChatGroupClient {
// 定义相关的属性
private final String HOST = "127.0.0.1"; // 服务器IP
private final int PORT = 6666; // 服务器端口
private Selector selector;
private SocketChannel socketChannel;
private String username;
// 构造器,完成初始化
public ChatGroupClient() throws IOException {
selector = Selector.open();
// 连接服务器
socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
// 设置非阻塞
socketChannel.configureBlocking(false);
// 将channel 注册到Selector
socketChannel.register(selector, SelectionKey.OP_READ);
// 获取Username
username = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(username + " is ok...");
}
// 向服务器发送消息
private void sendMsg(String msg) {
msg = username + " 说:" + msg;
try {
socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
} catch (IOException exception) {
exception.printStackTrace();
}
}
// 读取从服务器回传的消息
private void readMsg() {
try {
int readChannels = selector.select();
if (readChannels > 0) { // 有可用的通道
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isReadable()) {
// 得到相关通道
SocketChannel socketChannel = (SocketChannel) key.channel();
// 得到一个Buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 读取
socketChannel.read(buffer);
// 把读取到的缓存区数据转换成字符串
String msg = new String(buffer.array());
System.out.println(msg.trim());
}
// 删除当前的Key,防止重复操作
iterator.remove();
}
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
public static void main(String[] args) {
// 启动客户端
try {
ChatGroupClient client = new ChatGroupClient();
// 启动一个线程,每隔3秒,读取从服务端发送的数据
new Thread(() -> {
while (true){
client.readMsg();
try {
Thread.sleep(3_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
// 发送数据给服务端
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String msg = scanner.nextLine();
client.sendMsg(msg);
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
测试
server
client1
client2
client3