JAVA NIO实现简单聊天室功能

JAVA NIO实现简单聊天室功能

在JAVA NIO(New IO)中,实现简单聊天室功能通常需要以下步骤:

1. 创建ServerSocketChannel/IoServerSocketChannel实例

在JAVA NIO中,ServerSocketChannel和IoServerSocketChannel类分别充当服务器端的套接字通道。需要通过这两个类的实例来处理客户端请求的连接。

示例代码:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress("127.0.0.1",8080));

2. 创建Selector对象

Selector对象用来统一管理I/O事件的注册、删除以及处理等操作。

示例代码:

Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

3. 监听连接请求

在ServerSocketChannel/IoServerSocketChannel实例中调用accept()方法,通过Selector管理Accept操作。

示例代码:

while(true) {
    selector.select();
    Set<SelectionKey> selectionKeySet= selector.keys();
    for(SelectionKey selectionKey : selectionKeySet) {
        if(selectionKey.isAcceptable()) {
            SocketChannel channel = ((ServerSocketChannel)selectionKey.channel()).accept();
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
        }
    }
}

4. 处理连接请求

在连接被建立成功之后,就需要处理请求发送的信息。客户端向服务器请求的是一个聊天室连接,所以需要实现数据的读取、转发、以及广播等功能。

示例代码:

while(true) {
    selector.select();
    Set<SelectionKey> selectionKeySet= selector.keys();
    for(SelectionKey selectionKey : selectionKeySet) {
        if(selectionKey.isAcceptable()) {
            SocketChannel channel = ((ServerSocketChannel)selectionKey.channel()).accept();
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
        }else if(selectionKey.isReadable()) {
            SocketChannel channel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            channel.read(byteBuffer);
            String message = new String(byteBuffer.array(), StandardCharsets.UTF_8);
            System.out.println("receive message:"+message);
            for(SelectionKey key : selectionKeySet) {
                Channel targetChannel = key.channel();
                if(targetChannel instanceof SocketChannel && targetChannel != channel) {
                    ((SocketChannel) targetChannel).write(ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)));
                }
            }
        }
    }
}

示例1:客户端发送信息并广播

public static void main(String[] args) throws IOException, InterruptedException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8080));
        socketChannel.configureBlocking(false);
        while(!socketChannel.finishConnect() ){//自旋
        }
        Thread thread = new Thread(() -> {
            while(true) {
                ByteBuffer buf = ByteBuffer.allocate(1024);
                try {
                    socketChannel.read(buf);
                    buf.flip();
                    String data = new String(buf.array()).trim();
                    System.out.println("服务端回送的数据:"+data);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
        Scanner scanner = new Scanner(System.in);
        thread.start();
        String line = "";
        while (!line.equals("quit")) {
            line = scanner.nextLine();
            ByteBuffer buffer = ByteBuffer.wrap(line.getBytes(StandardCharsets.UTF_8));
            socketChannel.write(buffer);
        }
        socketChannel.close();
    }

示例2:客户端接收来自服务端的广播信息

public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8080));
        socketChannel.configureBlocking(false);
        while(!socketChannel.finishConnect() ){//自旋
        }

        ByteBuffer buf = ByteBuffer.allocate(1024);
        int count = 0;
        while((count = socketChannel.read(buf))>=0) {
            buf.flip();
            String message = new String(buf.array(),0,count,StandardCharsets.UTF_8);
            System.out.println("receive message:"+message);
        }
        socketChannel.close();
    }

以上就是JAVA NIO实现简单聊天室功能的完整攻略。

阅读剩余 65%

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JAVA NIO实现简单聊天室功能 - Python技术站

(0)
上一篇 2023年6月27日
下一篇 2023年6月27日

相关文章

  • Vue插槽的作用

    Vue插槽的作用 Vue插槽是一种强大的功能,用于在Vue组件中定义可重用的模板部分。它允许我们在组件中插入内容,从而实现更灵活的组件复用和定制化。 默认插槽 默认插槽是Vue插槽的基本形式。它允许我们在组件的模板中插入内容,并在组件中使用该内容。以下是一个示例: <template> <div> <h1>组件标题<…

    other 2023年8月21日
    00
  • matlab实现高斯滤波

    当然,我可以为您提供有关“Matlab实现高斯滤波”的完整攻略,以下是详细说明: 什么是高斯滤波? 高斯滤波是一种线性平滑滤波器,它可以有效地去除图中的噪,同时保留图像的边缘信息。高斯滤波器的核心思想是使用高斯函数作为滤波器的卷积,对像进行卷积运算,从而实平滑滤波的效果。 Matlab实现高斯滤波 以下是Matlab实现高斯滤波基本步骤: 读取图像 matl…

    other 2023年5月7日
    00
  • hp-socket快速入门:分包、粘包解析

    下面是HP-Socket快速入门:分包、粘包解析的完整攻略。 1.前言 在使用HP-Socket进行开发时,我们经常会遇到TCP协议在通信过程中会出现粘包、拆包问题。为了解决这个问题,我们必须在代码中进行处理。本文将详细讲解如何使用HP-Socket处理TCP粘包、拆包的问题。 2.分包处理 分包是指将TCP数据进行分开传输,以解决TCP粘包问题。下面我们就…

    其他 2023年4月16日
    00
  • ios14.6更新了什么 苹果ios14.6更新内容一览

    iOS 14.6 更新内容一览 苹果于2023年5月发布了 iOS 14.6 更新,该更新带来了一些新功能、改进和修复。以下是 iOS 14.6 更新的详细内容: 1. Apple Music 空间音频(Spatial Audio)支持:iOS 14.6 引入了空间音频功能,使 Apple Music 用户能够享受到更加沉浸式的音频体验。空间音频通过利用头部…

    other 2023年8月3日
    00
  • SpringBoot集成Jasypt敏感信息加密的操作方法

    下面我将详细讲解“SpringBoot集成Jasypt敏感信息加密的操作方法”的完整攻略。这份攻略分为以下几个部分: Jasypt简介和使用场景 集成Jasypt加密到SpringBoot应用 添加加密注解和使用示例 修改配置文件中的敏感信息为加密的值 1. Jasypt简介和使用场景 Jasypt是一个用于加密和解密敏感数据的Java框架,其提供了各种加密…

    other 2023年6月26日
    00
  • layui动态绑定事件的方法

    一、概述 Layui是一款非常流行的前端UI框架,通过Layui可以非常方便地搭建网站前端。在Layui中,我们常常需要为某些元素动态绑定事件,例如给一个按钮绑定点击事件,但是如果使用传统的添加事件监听函数的方式可能会出现问题,这时候我们就需要动态绑定事件了。 二、动态绑定事件的方法 在Layui中,我们可以使用 done 函数来实现动态绑定事件的效果。具体…

    other 2023年6月27日
    00
  • Android实现读取SD卡下所有TXT文件名并用listView显示出来的方法

    下面是实现读取SD卡下所有TXT文件名并用listView显示出来的方法的攻略: 确认权限 首先我们需要在AndroidManifest.xml中添加读取SD卡权限: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 获取SD…

    other 2023年6月27日
    00
  • 如何查询自己的ip地址 查询自己电脑的ip地址的方法

    如何查询自己的IP地址 要查询自己的IP地址,可以按照以下步骤进行操作: 方法一:使用命令提示符(Windows) 打开命令提示符。可以通过按下Win + R键,在弹出的运行窗口中输入\”cmd\”,然后点击\”确定\”来打开命令提示符。 在命令提示符窗口中,输入\”ipconfig\”命令,并按下回车键。 在输出结果中,查找\”IPv4 地址\”或\”IP…

    other 2023年7月29日
    00
合作推广
合作推广
分享本页
返回顶部