Netty学习笔记十二、NIO 网络编程应用-群聊系统代码实现

一、服务端

package com.hao.demo.netty.groupchat;

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

/**
 * @author haoxiansheng
 * @date 2020-05-18
 */
public class GroupChatServer {

    // 定义属性
    private Selector selector = null;

    private ServerSocketChannel listenChannel;

    private static final int PORT = 6667;

    // 构造器 完成初始化工作
    public GroupChatServer() {
        try {
            // 得到选择器
            selector = Selector.open();
            // ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            // 绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置非阻塞模式
            listenChannel.configureBlocking(false);
            // 将listenChannel 注册到selector上
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (IOException e) {
            e.fillInStackTrace();
        }
    }


    // 监听
    public void listen() {
        try {

            // 循环处理
            while (true) {
                int count = selector.select(2000);
                if (count > 0) { // 说明有事件处理
                    // 遍历selectionKeys
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        // 取出selectionKey
                        SelectionKey key = iterator.next();
                        // 监听到accept
                        if (key.isAcceptable()) {
                            SocketChannel socketChannel = listenChannel.accept();
                            // 设置非阻塞模式
                            socketChannel.configureBlocking(false);
                            // 将socketChannel注册到selector
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            // 提示
                            System.out.println(socketChannel.getRemoteAddress() + "上线");
                        }
                        if (key.isReadable()) { // 通道发生读事件,通道可读
                            // 处理读 (专门处理这个逻辑)
                            readData(key);
                        }

                        // 将当前的key 删除防止从新操作
                        iterator.remove();
                    }

                } else {
                    System.out.println("等待中。。。。。");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    // 读取客户端消息
    private void readData(SelectionKey key) {
        // 定义一个SocketChannel
        SocketChannel socketChannel = null;
        try {
            // 得到channel
            socketChannel = (SocketChannel) key.channel();

            // 创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            int count = socketChannel.read(buffer);

            // 根据count的值做处理
            if (count > 0) {
                // 把缓冲区的数据转成字符串 输出信息
                String msg = new String(buffer.array());
                System.out.println("from 客户端" + msg);

                // 向其他的客户端转发消息(去掉自己),专门写一个方法来处理
                sendToOtherClient(msg, socketChannel);
            }

        } catch (IOException e) {
            try {
                System.out.println(socketChannel.getRemoteAddress() + "离线");
                // 取消注册
                key.cancel();
                // 关闭通道
                socketChannel.close();
            } catch (IOException e1) {
                e1.fillInStackTrace();
            }

        }

    }


    // 转发消息到其他客户端
    private void sendToOtherClient(String msg, SocketChannel self) throws IOException {

        System.out.println("服务器转发消息");
        // 遍历所有注册到selector 上的SocketChannel 并排除自己

        for (SelectionKey key : selector.keys() ) {
            // 通过key 取出对应的SocketChannel
            Channel targetChannel = key.channel();
            // 排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {

                // 转型
                SocketChannel dest = (SocketChannel) targetChannel;
                // 将信息存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                // 将buffer 的数据写入通道
                dest.write(buffer);
            }
        }

    }

    public static void main(String[] args) {
        // 创建服务器对象
        GroupChatServer chatServer = new GroupChatServer();
        // 监听
        chatServer.listen();

    }
}

二、客户端

 

由于我自己idea 一个client不能启动多次 所以自己创建了三个一样方法的类。

1、client1

package com.hao.demo.netty.groupchat;

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 haoxiansheng
 * @date 2020-05-18
 */
public class GroupChatClient {

    private final String HOST = "127.0.0.1"; // 服务器地址

    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("客户端准备好了");
    }

    // 向服务器发送消息
    public void sendInfo(String info) {
        info = userName + "say" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.fillInStackTrace();
        }
    }

    // 从服务器回复的消息
    public void readInfo() {
        try {
            int readChannel = selector.select();
            if (readChannel > 0) { // 有可用通道

                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        // 得到相关通道
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        // 得到一个buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        // 读取
                        socketChannel.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove(); //删除当前的SelectionKey 防止重复操作
            } else {
                //System.out.println("没有可用的通道");

            }

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public static void main(String[] args) throws IOException {
        // 启动客户端
        GroupChatClient chatClient = new GroupChatClient();

        // 启动一个线程
        new Thread(() -> {
            while (true) {
                chatClient.readInfo();
                try {
                    Thread.currentThread().sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 发送数据
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            chatClient.sendInfo(msg);
        }
    }


}

2、client2

package com.hao.demo.netty.groupchat;

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 haoxiansheng
 * @date 2020-05-18
 */
public class GroupChatClient2 {

    private final String HOST = "127.0.0.1"; // 服务器地址

    private final int PORT = 6667; // 端口

    private Selector selector;

    private SocketChannel socketChannel;

    private String userName;

    public GroupChatClient2() 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("客户端准备好了");
    }

    // 向服务器发送消息
    public void sendInfo(String info) {
        info = userName + "say" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.fillInStackTrace();
        }
    }

    // 从服务器回复的消息
    public void readInfo() {
        try {
            int readChannel = selector.select();
            if (readChannel > 0) { // 有可用通道

                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        // 得到相关通道
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        // 得到一个buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        // 读取
                        socketChannel.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove(); //删除当前的SelectionKey 防止重复操作
            } else {
                //System.out.println("没有可用的通道");

            }

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public static void main(String[] args) throws IOException {
        // 启动客户端
        GroupChatClient2 chatClient = new GroupChatClient2();

        // 启动一个线程
        new Thread(() -> {
            while (true) {
                chatClient.readInfo();
                try {
                    Thread.currentThread().sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 发送数据
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            chatClient.sendInfo(msg);
        }
    }


}

3、client3

package com.hao.demo.netty.groupchat;

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 haoxiansheng
 * @date 2020-05-18
 */
public class GroupChatClient3 {

    private final String HOST = "127.0.0.1"; // 服务器地址

    private final int PORT = 6667; // 端口

    private Selector selector;

    private SocketChannel socketChannel;

    private String userName;

    public GroupChatClient3() 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("客户端准备好了");
    }

    // 向服务器发送消息
    public void sendInfo(String info) {
        info = userName + "say" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.fillInStackTrace();
        }
    }

    // 从服务器回复的消息
    public void readInfo() {
        try {
            int readChannel = selector.select();
            if (readChannel > 0) { // 有可用通道

                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        // 得到相关通道
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        // 得到一个buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        // 读取
                        socketChannel.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove(); //删除当前的SelectionKey 防止重复操作
            } else {
                //System.out.println("没有可用的通道");

            }

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public static void main(String[] args) throws IOException {
        // 启动客户端
        GroupChatClient3 chatClient = new GroupChatClient3();

        // 启动一个线程
        new Thread(() -> {
            while (true) {
                chatClient.readInfo();
                try {
                    Thread.currentThread().sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 发送数据
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            chatClient.sendInfo(msg);
        }
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值