|
|
@@ -0,0 +1,96 @@
|
|
|
+package space.anyi.chatClient;
|
|
|
+
|
|
|
+import java.io.Closeable;
|
|
|
+import java.io.IOException;
|
|
|
+import java.net.SocketException;
|
|
|
+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.Objects;
|
|
|
+import java.util.Set;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @ProjectName: chat-gwng
|
|
|
+ * @FileName: ReadHandler
|
|
|
+ * @Author: 杨逸
|
|
|
+ * @Data:2025/9/22 19:20
|
|
|
+ * @Description:
|
|
|
+ */
|
|
|
+public class ReadHandler implements Runnable, Closeable {
|
|
|
+ private Selector readSelector;
|
|
|
+ private boolean isExit = false;
|
|
|
+
|
|
|
+ public ReadHandler(Selector readSelector) {
|
|
|
+ this.readSelector = readSelector;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void close() throws IOException {
|
|
|
+ exit();
|
|
|
+ System.out.println("close readHandler");
|
|
|
+ if (Objects.nonNull(readSelector) && readSelector.isOpen()) {
|
|
|
+ readSelector.close();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void exit() {
|
|
|
+ isExit = true;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void run() {
|
|
|
+ System.out.println("readHandler starter");
|
|
|
+ while(true){
|
|
|
+ if (isExit)break;
|
|
|
+ int select = 0;
|
|
|
+ try {
|
|
|
+ select = readSelector.select(100);
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ if (select > 0) {
|
|
|
+ Set<SelectionKey> selectionKeys = readSelector.selectedKeys();
|
|
|
+ for (SelectionKey selectionKey : selectionKeys) {
|
|
|
+ if (selectionKey.isReadable() && selectionKey.isValid()) {
|
|
|
+ //拿到channel
|
|
|
+ SelectableChannel channel = selectionKey.channel();
|
|
|
+ SocketChannel socketChannel = (SocketChannel) channel;
|
|
|
+ //读取数据
|
|
|
+ ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
|
|
|
+ int len = 0;
|
|
|
+ try {
|
|
|
+ len = socketChannel.read(byteBuffer);
|
|
|
+ } catch (SocketException e) {
|
|
|
+ //连接意外中断导致异常
|
|
|
+ e.printStackTrace();
|
|
|
+ selectionKey.cancel();
|
|
|
+ try {
|
|
|
+ //关闭相关的channel
|
|
|
+ socketChannel.close();
|
|
|
+ } catch (IOException ex) {
|
|
|
+ ex.printStackTrace();
|
|
|
+ }
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ byteBuffer.flip();
|
|
|
+ if (len > 0) {
|
|
|
+ String msg = new String(byteBuffer.array(), 0, len);
|
|
|
+ System.out.println(msg);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ //处理完,移除selectionKey
|
|
|
+ selectionKeys.remove(selectionKey);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ //关闭资源
|
|
|
+ try {
|
|
|
+ close();
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|