java基于NIO实现群聊模式

Java基于NIO实现群聊模式攻略

简介

Java NIO(New I/O)是Java 1.4版本引入的一组用于高效处理I/O操作的API。使用Java NIO,我们可以实现非阻塞的、事件驱动的I/O操作,这对于实现群聊模式非常有用。在本攻略中,我们将使用Java NIO来实现一个简单的群聊程序。

步骤

步骤1:创建服务器端

首先,我们需要创建一个服务器端来接收客户端的连接,并将接收到的消息广播给所有连接的客户端。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class Server {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private ByteBuffer buffer = ByteBuffer.allocate(1024);

    public void start(int port) throws IOException {
        selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(port));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println(\"Server started on port \" + port);

        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isAcceptable()) {
                    acceptConnection(key);
                } else if (key.isReadable()) {
                    broadcastMessage(key);
                }
            }
        }
    }

    private void acceptConnection(SelectionKey key) throws IOException {
        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
        SocketChannel clientChannel = serverChannel.accept();
        clientChannel.configureBlocking(false);
        clientChannel.register(selector, SelectionKey.OP_READ);
        System.out.println(\"New client connected: \" + clientChannel.getRemoteAddress());
    }

    private void broadcastMessage(SelectionKey key) throws IOException {
        SocketChannel clientChannel = (SocketChannel) key.channel();
        buffer.clear();
        int bytesRead = clientChannel.read(buffer);
        if (bytesRead == -1) {
            clientChannel.close();
            return;
        }
        buffer.flip();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        String message = new String(bytes);
        System.out.println(\"Received message: \" + message);

        for (SelectionKey selectionKey : selector.keys()) {
            Channel channel = selectionKey.channel();
            if (channel instanceof SocketChannel && channel != clientChannel) {
                SocketChannel destChannel = (SocketChannel) channel;
                destChannel.write(ByteBuffer.wrap(bytes));
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.start(8080);
    }
}

步骤2:创建客户端

接下来,我们需要创建一个客户端来连接服务器,并发送和接收消息。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class Client {
    private SocketChannel socketChannel;
    private ByteBuffer buffer = ByteBuffer.allocate(1024);

    public void start(String serverHost, int serverPort) throws IOException {
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress(serverHost, serverPort));

        while (!socketChannel.finishConnect()) {
            // 等待连接完成
        }

        System.out.println(\"Connected to server: \" + socketChannel.getRemoteAddress());

        new Thread(() -> {
            try {
                while (true) {
                    buffer.clear();
                    int bytesRead = socketChannel.read(buffer);
                    if (bytesRead == -1) {
                        socketChannel.close();
                        return;
                    }
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    String message = new String(bytes);
                    System.out.println(\"Received message: \" + message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (true) {
            String message = scanner.nextLine();
            if (message.equalsIgnoreCase(\"exit\")) {
                socketChannel.close();
                break;
            }
            buffer.clear();
            buffer.put(message.getBytes());
            buffer.flip();
            socketChannel.write(buffer);
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client();
        client.start(\"localhost\", 8080);
    }
}

示例说明

示例1:运行服务器端

Server server = new Server();
server.start(8080);

示例2:运行客户端

Client client = new Client();
client.start(\"localhost\", 8080);

在示例2中,客户端将连接到本地主机的8080端口,并可以发送和接收消息。在服务器端示例1中,服务器将监听8080端口,并将接收到的消息广播给所有连接的客户端。

请注意,示例中的代码仅为演示目的,可能需要根据实际需求进行修改和扩展。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java基于NIO实现群聊模式 - Python技术站

(0)
上一篇 2023年7月29日
下一篇 2023年7月29日

相关文章

  • js鼠标滚轮事件解析

    JS鼠标滚轮事件解析 鼠标滚轮是我们日常使用计算机时,最为常用的交互方式之一。在Web开发中,通过JavaScript的事件监听机制,我们可以监听鼠标的滚轮事件,来实现各种滚动交互效果。本文将对JavaScript中的鼠标滚轮事件进行解析,包括事件绑定、事件对象和兼容处理等相关内容。 事件绑定 在JavaScript中,我们通常使用addEventListe…

    其他 2023年3月28日
    00
  • Win11无限重启怎么办 Win11系统自动重启解决办法

    Win11无限重启怎么办 问题描述 在使用Win11系统时,有时可能会出现无限重启的情况,即计算机会在启动过程中不断地重启。这种情况会给用户带来极大的困扰,用户需要采取一些解决办法来解决。 解决办法 1.关闭自动重启 如果Win11系统在启动过程中循环重启,用户可以在计算机进入“安全模式”后,关闭自动重启功能。具体方法如下: 在计算机启动时按下 F8 按键,…

    other 2023年6月26日
    00
  • 如何让虚拟机访问外网

    当我们在虚拟机中进行开发或测试时,需要让虚拟机访问外网,以便下载软件、更新系统等操作。以下是关于如何让虚机访问外网的完整攻略: 确认虚拟机网络连接方式 在让虚拟机访问外网之前,需要确认虚机的网络连接方式。虚拟机可以使用桥接模式、NAT模式或者Host-Only模式进行网络连接。其中,桥接模式可以让虚拟机直接连接到物理网络中,NAT模式可以让虚拟机通过主机网络…

    other 2023年5月9日
    00
  • 安装vmtools失败的三类解决方法(windows、linux、macos)

    以下是关于“安装vmtools失败的三类解决方法(Windows、Linux、macOS)”的完整攻略: Windows系统 方法1:手动安装 如果自动安装tools,可以尝试手动安装。可以使用以下步骤手动安装vmtools: 在VMware菜单中,选择“虚拟机>“安装VMware Tools”。 在虚拟机中,打开CD/DVD驱动器,找到VMware …

    other 2023年5月7日
    00
  • Windows Server 2019和Windows Server, Version 1909的区别是什么

    Windows Server 2019和Windows Server, Version 1909是微软公司发布的两个Windows Server产品,它们之间存在一些区别和特性。本文将详细讲解它们之间的区别和如何选择。 区别 产品版本 Windows Server 2019是微软公司发布的最新版本,它是Windows Server产品系列的第九个主要版本。而…

    other 2023年6月27日
    00
  • 利用opencv实现图片的配准/对齐

    以下是关于“利用opencv实现图片的配准/对齐”的完整攻略,包含两个示例。 背景 图像配准/对齐是指将多图像中的相同场景进行对齐,使得它们在像素级别上对应。在计算机视觉领域,图像配准/对齐是一个重要的问题。OpenCV是一个流行的计算机视觉库,它提供了许多图像配准/对齐的算法和工具。 安装 在使用OpenCV之前,我们需要先安装它。具体步骤如下: 安装Op…

    other 2023年5月9日
    00
  • hue安装与使用

    以下是“Hue安装与使用的完整攻略”的标准markdown格式文本,其中包含了两个示例说明: Hue安装与使用 Hue是一个开源的Web界面,用于管理Apache Hadoop集群。本文将介绍如何安装和使用Hue,包括如何安装Hue、如何配置Hue和如何使用Hue。 1. 安装Hue 以下是安装Hue的步骤: 下载Hue的安装包。 解压缩安装包。 进入解压缩…

    other 2023年5月10日
    00
  • netty中pipeline的handler添加删除分析

    Netty中的Pipeline是一种实现消息传递的机制。Pipeline是Netty中用来处理输入和输出的一系列处理器的有序集合。Pipeline由一个ChannelHandlerContext链组成,每个ChannelHandlerContext包装了一个ChannelHandler。在消息从Channel中进入Pipeline后,它将顺序地被每个Chan…

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