NIO实现聊天室

参考自尚硅谷视频

服务端代码

**package service;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author huqy
 */
public class ChatServer {


    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        InetSocketAddress address = new InetSocketAddress(8888);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(address);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务器启动--->");
        while (true) {
            int select = selector.select();
            if (select == 0) {
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel accept = ssc.accept();
                    System.out.println("访问者--->" + accept.getRemoteAddress());
                    accept.configureBlocking(false);
                    accept.register(selector, SelectionKey.OP_READ);
                    accept.write(ByteBuffer.wrap("欢迎进入聊天室".getBytes()));
                } else if (selectionKey.isReadable()) {
                    SocketChannel sc = (SocketChannel) selectionKey.channel();
                    ByteBuffer bf = ByteBuffer.allocate(1024);
                    StringBuilder messge = new StringBuilder();
                    while (sc.read(bf) > 0) {
                        bf.flip();
                        messge.append(Charset.forName(StandardCharsets.UTF_8.name()).decode(bf));
                    }
                    if (messge.toString().equals("")) {
                        continue;
                    }
                    //广播群发
                    Set<SelectionKey> keys = selector.keys();
                    for (SelectionKey key : keys) {
                        SelectableChannel tr = key.channel();
                        if (tr == sc){
                            continue;
                        }
                        if (tr instanceof SocketChannel trSc){
                            System.out.println("发送信息给-->"+trSc.getRemoteAddress()+"-->message: "+ messge);
                            trSc.write(ByteBuffer.wrap(messge.toString().getBytes()));
                        }
                    }
                }
            }
        }
    }
}

客户端

package client;

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.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @Author huqy
 */
public class ChatClient {

    public static void main(String[] args) throws IOException {
        InetSocketAddress address = new InetSocketAddress(8888);
        SocketChannel sc = SocketChannel.open(address);
        sc.configureBlocking(false);
        Selector selector = Selector.open();
        sc.register(selector, SelectionKey.OP_READ);
        new Thread(new Read(selector)).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String message = scanner.nextLine();
            if (message.length() > 0) {
                sc.write(Charset.forName(StandardCharsets.UTF_8.name()).encode(message));
            }
        }
    }

    public static class Read implements Runnable {

        Selector selector;

        Read(Selector selector) {
            this.selector = selector;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    int select = selector.select();
                    if (select == 0) {
                        continue;
                    }
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        iterator.remove();
                        if (selectionKey.isReadable()) {
                            SocketChannel sc = (SocketChannel) selectionKey.channel();
                            ByteBuffer bf = ByteBuffer.allocate(1024);
                            StringBuilder messge = new StringBuilder();
                            while (true) {
                                if (!(sc.read(bf) > 0)) break;
                                bf.flip();
                                messge.append(Charset.forName(StandardCharsets.UTF_8.name()).decode(bf));
                                System.out.println(messge);
                            }
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值