网络编程NIO:BIO和NIO详解,看不懂你打我( 四 )
【网络编程NIO:BIO和NIO详解,看不懂你打我】//客户端public class GroupChatClient {private final static String SEVER_HOST = "127.0.0.1";//连接的客户端主机private final static int SEVER_PORT = 6666;//连接的客户端端口private Selector selector;//选择器private SocketChannel socketChannel;private String username;//储存客户端ip地址public GroupChatClient(){try {selector = Selector.open();//开启选择器socketChannel = SocketChannel.open(new InetSocketAddress(SEVER_HOST, SEVER_PORT));//开启通道socketChannel.configureBlocking(false);//将通道设为非阻塞socketChannel.register(selector, SelectionKey.OP_READ);//将通道注册在选择器上 , 事件类型为读username = socketChannel.getLocalAddress().toString().substring(1);//获取客户端ip地址String message = " 进入聊天群!";sendMessage(message);}catch (IOException e){e.printStackTrace();}}//发送消息public void sendMessage(String message){message = username+": "+message;try{ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes());socketChannel.write(byteBuffer);}catch (IOException e){e.printStackTrace();}}//读取从服务器转发送过来的消息public void readMessage(){try{int read = selector.select();if (read > 0){Iterator keyIterator = selector.selectedKeys().iterator();while (keyIterator.hasNext()){SelectionKey key = keyIterator.next();if (key.isReadable()){SocketChannel socketChannel = (SocketChannel)key.channel();ByteBuffer byteBuffer = ByteBuffer.allocate(1024);socketChannel.read(byteBuffer);System.out.println(new String(byteBuffer.array()));}keyIterator.remove();}}}catch (IOException e){e.printStackTrace();}}public static void main(String[] args) {final GroupChatClient groupChatClient = new GroupChatClient();//客户端开启一个线程来监听是否有服务器转发来消息new Thread(){@Overridepublic void run() {while (true){groupChatClient.readMessage();try {Thread.currentThread().sleep(1000);}catch (InterruptedException e){e.printStackTrace();}}}}.start();Scanner scanner = new Scanner(System.in);while (scanner.hasNextLine()){String message = scanner.nextLine();groupChatClient.sendMessage(message);}}}
- EVGA RTX3080更新BIOS 显卡功耗提升至450W
- 华硕发布400系主板新BIOS:Intel酷睿也支持AMD SAM了
- 常用的NIO框架-Netty
- OS|蔚来发布NIO OS 2.8.0版本更新 11月30日分批推送
- 技嘉500系列主板升级BIOS:3A平台打鸡血 性能白捡17%
- AMD RX 6900 XT BIOS信息曝光:最高GPU时钟频率3.0GHz
- 参与|CompanionPro:无需人参与的狗狗AI训练机器
- Apple|摩托罗拉新机 Nio 曝光,Apple M1 芯片安兔兔跑分曝光
- 摩托罗拉|摩托罗拉Nio智能手机传搭配105Hz刷新率显示屏
- 摩托罗拉Nio智能手机传搭配105Hz刷新率显示屏