|
|
@@ -28,6 +28,7 @@ public class ChatServer implements Runnable, Closeable {
|
|
|
private Selector acceptSelector;
|
|
|
private Selector readSelector;
|
|
|
private ReadHandler readHandler;
|
|
|
+ private WriteHandler writeHandler;
|
|
|
private boolean isExit = false;
|
|
|
|
|
|
public ChatServer(int port) throws IOException {
|
|
|
@@ -42,6 +43,9 @@ public class ChatServer implements Runnable, Closeable {
|
|
|
this.readSelector = Selector.open();
|
|
|
//自定义读事件处理器,用处理客户端发送的消息
|
|
|
this.readHandler = new ReadHandler(readSelector);
|
|
|
+ this.writeHandler = new WriteHandler(readSelector);
|
|
|
+ //读取到数据后需要,写数据的能力
|
|
|
+ readHandler.setWriteHandler(writeHandler);
|
|
|
}
|
|
|
|
|
|
|
|
|
@@ -102,42 +106,32 @@ public class ChatServer implements Runnable, Closeable {
|
|
|
* @data:2025/09/22 19:25:58
|
|
|
* @since 1.0.0
|
|
|
*/
|
|
|
- public void broadcast(String msg){
|
|
|
- //获取所有的key
|
|
|
- Set<SelectionKey> keys = readSelector.keys();
|
|
|
- for (SelectionKey key : keys) {
|
|
|
- SocketChannel channel = (SocketChannel) key.channel();
|
|
|
- try {
|
|
|
- //发信息
|
|
|
- channel.write(ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)));
|
|
|
- } catch (IOException e) {
|
|
|
- e.printStackTrace();
|
|
|
- }
|
|
|
- }
|
|
|
+ public void broadcast(String msg) {
|
|
|
+ writeHandler.broadcast(msg);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* @param msg 信息
|
|
|
- * @param target 目标
|
|
|
+ * @param target 目标的channel
|
|
|
* @description: 发送私聊信息
|
|
|
* @author: 杨逸
|
|
|
* @data:2025/09/22 19:31:09
|
|
|
* @since 1.0.0
|
|
|
*/
|
|
|
- public void sendMessageWithPrivate(String msg,String target){
|
|
|
- //todo
|
|
|
+ public void sendMessageWithPrivate(String msg,SocketChannel target){
|
|
|
+ writeHandler.sendMessageWithPrivate(msg,target);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* @param msg 信息
|
|
|
- * @param group 群
|
|
|
+ * @param form 发起人的连接channel
|
|
|
* @description: 群发信息
|
|
|
* @author: 杨逸
|
|
|
* @data:2025/09/22 19:32:08
|
|
|
* @since 1.0.0
|
|
|
*/
|
|
|
- public void sendMessageWithGroup(String msg,String group){
|
|
|
- //todo
|
|
|
+ public void sendMessageWithGroup(String msg,SocketChannel form){
|
|
|
+ writeHandler.sendMessageWithGroup(msg,form);
|
|
|
}
|
|
|
|
|
|
@Override
|