NIO网络编程简单应用实例

实例要求

  1. 编写一个NIO群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
  2. 实现多人群聊
  3. 服务器端: 可以检测用户上线,离线,并实现消息转发功能
  4. 客户端: 通过channel可以无阻塞发送消息给其他所有用户,同时可以接受其他用户发送的消息(有服务器转发得到)
  5. 目的: 进一步理解NIO非阻塞网络编程机制

服务器端代码:

package com.ding.nio.groupchat;

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

public class GroupChatService {
    // 定义属性
    private Selector selector;

    private ServerSocketChannel listenChannel;

    private static final int PORT = 6667;

    // 构造器完成初始化任务


    public GroupChatService() {
        try {
            // 得到选择器
            selector = Selector.open();
            // ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            // 绑定监听的端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置非阻塞模式
            listenChannel.configureBlocking(false);
            // 注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 监听
    public void listen() {
        while (true) {
            // 循环监听
            try {
                int count = selector.select(2000);
                if (count == 0) {
                    System.out.println("等待中.....");
                }
                // 代表有事件处理
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                for (SelectionKey key : selectionKeys) {
                    // 监听到accept
                    if (key.isAcceptable()) {
                        SocketChannel socketChannel = listenChannel.accept();
                        socketChannel.configureBlocking(false);

                        // 获取当前连接的socket channel
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        // 给出提示 某某某上线了
                        System.out.println(socketChannel.getRemoteAddress() + "上线了");
                    }
                    if (key.isReadable()) {
                        // 通道发生read事件,即通道可读
                        readData(key);
                    }
                    // 把当前的key删除,防止重复处理
                    selectionKeys.remove(key);
                }
            } catch (IOException e) {
                e.printStackTrace();
                // 发生异常
                System.out.println("异常了,桀桀");
            } finally {
                System.out.println("结束一次");
            }
        }
    }

    // 读取客户端消息
    private void readData(SelectionKey key) {
        SocketChannel channel = null;
        try {
            // 先定义一个socketChannel
            channel = (SocketChannel) key.channel();
            // 创建缓冲buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            // 读取长度,根据count值处理
            int count = channel.read(byteBuffer);
            // 把缓冲区数据转成string
            if (count == 0) {
                return;
            }
            String msg = new String(byteBuffer.array());
            // 输出该消息
            System.out.println("from 客户端:" + msg);
            // 向其他客户端转发消息
            sendInfoToOtherClient(msg, channel);
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 可能已离线");
                // 取消注册
                key.cancel();
                // 关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    // 转发消息给其他的客户(排除自己)
    private void sendInfoToOtherClient(String msg,SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中....");
        //便利 所有注册到selector上的socketChannel,并排除自己
        // 获取所有在线的 connection
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        for (SelectionKey key : selectionKeys) {
            // 通过比较key 排除自己
            Channel targetChannel = key.channel();
            if (targetChannel instanceof  SocketChannel && targetChannel != self) {
                SocketChannel dest = (SocketChannel) targetChannel;
                // 将msg,存储进buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                dest.write(buffer);
            }
        }
    }
    public static void main(String[] args) {
        // 创建服务器对象
        GroupChatService groupChatService = new GroupChatService();
        groupChatService.listen();
    }
}

客户端代码

package com.ding.nio.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;
import java.util.Set;

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);
        // 将channel注册selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok");
    }

    //向服务器发送消息
    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 readChannels = selector.select();
            if (readChannels > 0) {
                // 代表有可以用的通道
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        // 得到相关的通道
                        SocketChannel sc = (SocketChannel) key.channel();
                        // 得到一个buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        // 读取
                        sc.read(buffer);
                        // 把读到的数据转成string
                        String msg = new String(buffer.array());
                        System.out.println("msg.trim() = " + msg.trim());
                    }
                    iterator.remove();
                }
            } else {
                System.out.println("没有可用的通道");
            }
        } catch (IOException e) {

        }
    }

    public static void main(String[] args) throws IOException {
        // 启动客户端
        GroupChatClient chatClient = new GroupChatClient();
        // 启动一个线程 , 每隔三秒读取数据
        new Thread() {
            public void run() {
                while (true) {
                    chatClient.readInfo();
                    try {
                        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、付费专栏及课程。

余额充值