java网络编程NIO聊天室基本实现

35 篇文章 0 订阅

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

/**
 *
 */
public class GroupChatServer {


    //定义成员变量
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private static final int PORT=6667;

    public GroupChatServer(){
        //初始化任务
        try {
            serverSocketChannel=ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞
            serverSocketChannel.configureBlocking(false);
            selector=Selector.open();
            //将socket注册到selector中
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen(){
        try {
            while (true){
                //阻塞2s
                int select = selector.select();
                if(select>0){
                    //有事件需要处理
                    Iterator<SelectionKey> selectionKeyIterator = selector.selectedKeys()
                            .iterator();
                    while (selectionKeyIterator.hasNext()){
                        SelectionKey selectionKey=selectionKeyIterator.next();
                        if(selectionKey.isAcceptable()){
                            //监听到连接事件
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector,SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress()+"已上线");
                        }
                        if(selectionKey.isReadable()){
                            readData(selectionKey);
                        }
                        //将当前的selectionKey删除 防止重复处理
                        selectionKeyIterator.remove();
                    }

                }else {
                    //没有事件处理
                    System.out.println("....等待");
                }



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

        }
    }

    /**
     *
     * @param selectionKey
     */
    private void readData(SelectionKey  selectionKey){
        SocketChannel socketChannel=null;
        try {
            //根据SelectionKey 获取对应的客户端的socketchannel
            socketChannel =(SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //从客户端获取数据到byteBuffer中
            int count = socketChannel.read(byteBuffer);
            if(count>0){
                //读取到数据 将缓冲区数据输出
                String message=new String(byteBuffer.array());
                System.out.println("from 客户端:"+message);
                //向其它客户端发送消息
                sendInfoToOtherClients(message,socketChannel);
            }
        }catch (IOException e){
            try {
                System.out.println(socketChannel.getRemoteAddress()+"离线了...");
                //取消注册
                selectionKey.cancel();
                //关闭通道
                socketChannel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }finally {

        }

    }

    //转发消息给其它的通道
    private void sendInfoToOtherClients(String message,SocketChannel self)
            throws IOException {
        System.out.println("服务器转发消息");
        //遍历所有注册到selector上的socketChannel并排除自己self
        for (SelectionKey selectionKey:selector.keys()){
            Channel targetChannel = selectionKey.channel();
            //排除自己self
            if(targetChannel instanceof SocketChannel&&targetChannel !=self){
                SocketChannel dest=(SocketChannel) targetChannel;
                ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes());
                //将buffer数据写入到通道
                dest.write(byteBuffer);
            }
        }

    }

    public static void main(String[] args) {
        GroupChatServer server=new GroupChatServer();
        server.listen();
    }

}

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;

/**
 */
public class GroupChatClient {

    private final String HOST="127.0.0.1";
    private final int PORT=6667;
    private String userName;
    private Selector selector;
    private  SocketChannel socketChannel;

    public GroupChatClient(){
        try {
            selector=Selector.open();
            socketChannel=SocketChannel.open(new InetSocketAddress(HOST,PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            userName=socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(userName+"client is ok");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //想服务端发送消息
    public void sendInfo(String info){
        info=userName+"说:"+info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //从服务端读取消息
    public void readInfo(){
        try {
            int select = selector.select();
            if(select>0){
                //通道有事件发生
                Iterator<SelectionKey> selectionKeyIterator = selector.selectedKeys()
                        .iterator();
                while (selectionKeyIterator.hasNext()){
                    SelectionKey selectionKey=selectionKeyIterator.next();
                    if(selectionKey.isReadable()){
                        SocketChannel readSocketChannel=(SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                        readSocketChannel.read(byteBuffer);
                        String msg=new String(byteBuffer.array());
                        System.out.println("客户端读取到的信息:"+msg);
                    }
                    selectionKeyIterator.remove();
                }
            }else {
            }

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

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

        // 启动一个线程 读取数据
        new Thread(()->{
            while (true){
                groupChatClient.readInfo();
                try {
                    Thread.currentThread().sleep(3000);
                }catch (Exception e){
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s=scanner.nextLine();
            groupChatClient.sendInfo(s);
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值