目标
完成一个群聊系统:
- 服务器可接收多个客户端的连接并接收信息
- 服务器向除了发送消息的客户端的其他客户端发送消息
- 客户端可以发送消息和接收消息
完成
服务器
package com.company.GroupChat;
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 GroupChatServer {
private final int Port = 9999;
//使用到的属性
private Selector selector;
private ServerSocketChannel serverSocketChannel;
private SocketChannel socketChannel;
//构造器完成服务器连接操作
public GroupChatServer() throws Exception {
//打开selector和serverSocketChannel
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
//设置非阻塞
serverSocketChannel.configureBlocking(false);
//监听端口
serverSocketChannel.socket().bind(new InetSocketAddress(Port));
//注册
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
//读取消息的方法
public static void main(String[] args) throws Exception {
GroupChatServer server = new GroupChatServer();
server.Listen();
}
//设置一个监听方法,监听事件
public void Listen() throws Exception {
while (true) {
int cout=selector.select();
//selector监控
if (cout > 0) {
//获得集合迭代器
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
//得到该SelectionKey
SelectionKey key = keyIterator.next();
//判断事件
if (key.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
//设置非阻塞
socketChannel.configureBlocking(false);
//注册,监听读事件
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("客户端:" + socketChannel.getRemoteAddress() + " 已上线");
}
if (key.isReadable()) {
send(key);
}
//移除已经处理的SelectionKey
keyIterator.remove();
}
}
//连接出现异常,应该是客户端下线
}
}
//发送消息
public void send(SelectionKey key) {
//得到Channel
SocketChannel channel = null;
//读取
try {
channel = (SocketChannel) key.channel();
//创建buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
int count = channel.read(buffer);
//读取到了信息
if (count > 0) {
String msg = new String(buffer.array());
System.out.println("客户端发送的消息:" + msg);
//转发消息
Forward(msg, channel);
}
} catch (IOException e) {
try {
System.out.println(channel.getRemoteAddress() + "已下线。。。");
//取消注册
key.cancel();
//关闭通道
channel.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
//转发消息的方法
//需要知道消息和自身通道(转发除自身外的通道)
public void Forward(String msg, SocketChannel self) throws IOException {
System.out.println("消息转发中。。。");
//得到所有注册在选择器上的通道
for (SelectionKey key : selector.keys()) {
//得到通道
Channel channel = key.channel();
//排除自己和非SocketChannel
if (channel instanceof SocketChannel && channel != self) {
SocketChannel sc = (SocketChannel) channel;
//创建buffer
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
//写入
sc.write(buffer);
}
}
}
}
客户端
package com.company.GroupChat;
import javafx.scene.transform.Scale;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
public class GroupChatClient {
//常用的属性
private final String IP="127.0.0.1";
private final int Port=9999;
private Selector selector;
private SocketChannel socketChannel;
private String clientname;
//构造方法
public GroupChatClient() throws Exception{
//打开
selector = Selector.open();
//连接
socketChannel = SocketChannel.open(new InetSocketAddress(IP,Port));
//设置非阻塞
socketChannel.configureBlocking(false);
//注册,监听read方法
socketChannel.register(selector, SelectionKey.OP_READ);
//得到客户端名字
clientname=socketChannel.getLocalAddress().toString().substring(1);
System.out.println(clientname+" 准备就绪。。。");
}
//接收信息
public void Receive() throws IOException {
int sel=selector.select();
//接收到事件
if (sel > 0){
//迭代得到的SelectionKey集合
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
//获得SelectionKey
SelectionKey key = iterator.next();
if (key.isReadable()){
//得到通道
SocketChannel channel = (SocketChannel)key.channel();
//buffer获得信息
ByteBuffer buffer = ByteBuffer.allocate(1024);
//从通道中读出
channel.read(buffer);
System.out.println(new String(buffer.array()));
}
iterator.remove();
}
}
else
System.out.println("没有可用通道");
}
public void Send(String str) throws IOException {
str=clientname+" : "+str;
ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
//写入
socketChannel.write(buffer);
}
public static void main(String[] args) throws Exception {
GroupChatClient chatClient=new GroupChatClient();
new Thread(){
public void run() {
while (true){
try {
chatClient.Receive();
Thread.currentThread().sleep(3000);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
//发送数据
Scanner scanner=new Scanner(System.in);
//一行一行的输入
while (scanner.hasNext()){
String msg=scanner.nextLine();
chatClient.Send(msg);
}
}
}
结果
完成的代码步骤都在注释里
实验结果:
客户端连接时打印上线消息
客户端发送消息:
服务器转发:
其他客户端接收消息: