企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
~~~ package com.youge.nio.chat.client; import java.io.IOException; 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.util.Iterator; import java.util.Scanner; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020/11/26 16:25 */ public class GroupChatClient { //定义相关的属性 private final String HOST = "127.0.0.1";//服务器ip private final int PORT = 6667;//服务器端口 private Selector selector; private SocketChannel socketChannel; private String username; /** * 初始化工作 */ public GroupChatClient() throws IOException { //获取选择器 selector = Selector.open(); //连接服务器 socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT)); //设置非阻塞 socketChannel.configureBlocking(false); //将socketChannel注册到selector上 socketChannel.register(selector, SelectionKey.OP_READ); //获取username username = socketChannel.getLocalAddress().toString().substring(1); System.out.println(username + " is ok ..."); } /** * 向服务器发送消息 * * @param info */ public void sendInfo(String info) { info = username + " 说: " + info; try { socketChannel.write(ByteBuffer.wrap(info.getBytes())); } catch (IOException e) { e.printStackTrace(); } } /** * 读取从服务器发送过来的消息 */ public void readInfo() { try { int count = selector.select(); if (count > 0) {//有可能的通道 Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isReadable()) {//可读 //得到相关通道 SocketChannel channel = (SocketChannel) key.channel(); //创建buffer容器 ByteBuffer buffer = ByteBuffer.allocate(1024); //把数据读取到buffer容器 channel.read(buffer); //把读取到的buffer转换为字符串 String msg = new String(buffer.array()); System.out.println(msg.trim()); } iterator.remove();//删除当前的selectionKey,防止重复操作 } } else { // System.out.println("没有可用的通道..."); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { //启动客户端 GroupChatClient client = new GroupChatClient(); //启动一个线程,每隔三秒,读取从服务器发送的数据 new Thread() { public void run() { while (true) { client.readInfo(); //休眠三秒 try { Thread.currentThread().sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); //发送数据给服务器 Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String line = scanner.nextLine(); client.sendInfo(line); } } } ~~~