Nio群聊Damo

package com.duing.chat;

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

public class ChatServer2 {
    //服务端通道
   private ServerSocketChannel socketChannel;

    //多路复用选择器
   private Selector selector;

    private ChatServer2() throws IOException {//初始化
        socketChannel=ServerSocketChannel.open();
        selector=Selector.open();

        SocketAddress socketAddress=new InetSocketAddress(6666);//设置端口号
        socketChannel.socket().bind(socketAddress);

        socketChannel.configureBlocking(false);
        //注册通道可接受事件
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void listenClient () throws IOException {
        System.out.println("服务端启动了......");
        //监听客户端的变化
        while (true){
            //询问 选择器 是否有事件要处理
            int select = selector.select();
            if (select>0){
                //获取要处理事件的集合
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){//判断有没有下一个
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    //识别key所对应的事件种类
                    if (key.isAcceptable()){
                        SocketChannel accept = socketChannel.accept();
                        accept.configureBlocking(false);
                        System.out.println("用户:"+accept.socket().getRemoteSocketAddress()+"上线了");
                        accept.register(selector,SelectionKey.OP_READ);//注册读事件
                        continue;
                    }
                    if (key.isReadable()){
                       this.ReadData(key);
                    }
                }
            }
        }
    }

public void ReadData(SelectionKey key){
    SocketChannel socketChannel=null;
    try {
        socketChannel=(SocketChannel) key.channel();
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        socketChannel.read(byteBuffer);
        byteBuffer.flip();
        String s=new String(byteBuffer.array());

        System.out.println(socketChannel.socket().getRemoteSocketAddress()+"用户mag:"+s);
        //再将数据广播给其他客户端  (不包括发送数据的客户端自身)
        sendToOther(s,socketChannel);

    }catch (Exception e){
        //没有获取到通道 即为用户下线了
        System.out.println("用户:"+socketChannel.socket().getRemoteSocketAddress()+"下线");//这是获取远程的一个地址
        //取消注册关系
        key.cancel();
        //关闭通道
        socketChannel.socket();
    }
}

public void sendToOther(String mag,SocketChannel socketChannel) throws IOException {
    //找到所有的通道,相当于找到了所有的在线用户
    Set<SelectionKey> keys = selector.keys();
    for (SelectionKey key : keys) {
        //判断这是一个用户 并不等价于selfchannel
         Channel channel=key.channel();
        if (channel instanceof SocketChannel && channel!=socketChannel){
            SocketChannel socketChannel1=(SocketChannel) channel;
            //wrap方法 直接将array数据 存放到选冲区
            ByteBuffer byteBuffer=ByteBuffer.wrap(mag.getBytes());
            socketChannel1.write(byteBuffer);
            byteBuffer.flip();
        }
    }
}

    public static void main(String[] args) {
        try {
            ChatServer2 server2=new ChatServer2();
            server2.listenClient();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

package com.duing.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
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 ChatClient2 {

    private SocketChannel socketChannel;
    private Selector selector;

    private ChatClient2() throws IOException {
        socketChannel=SocketChannel.open();
        SocketAddress socketAddress=new InetSocketAddress("127.0.0.1",6666);
        socketChannel=socketChannel.open(socketAddress);

        selector=Selector.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);

        System.out.println("用户:"+socketChannel.getLocalAddress()+"上线");
    }

    public void sendate(String mag) throws IOException {
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        byteBuffer.put(mag.getBytes());
         byteBuffer.flip();
        socketChannel.write(byteBuffer);
    }

    public void readData() throws IOException {
        int select = selector.select();
       if (select>0){
           Set<SelectionKey> selectionKeys = selector.selectedKeys();
           Iterator<SelectionKey> iterator = selectionKeys.iterator();
           while (iterator.hasNext()){
               SelectionKey next = iterator.next();
               if (next.isReadable()){
                 SocketChannel socketChannel=(SocketChannel) next.channel();
                  ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                  socketChannel.read(byteBuffer);
                  byteBuffer.flip();

                  String s=new String(byteBuffer.array());
                   System.out.println(socketChannel.socket().getRemoteSocketAddress()+"发送信息:"+s);
               }
           }
       }
    }

    public static void main(String[] args) throws IOException {
        final ChatClient2 chatClient2=new ChatClient2();
        new Thread(){
            @Override
            public void run() {
                try {
                    chatClient2.readData();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        Scanner scanner=new Scanner(System.in);
        while (scanner.hasNextLine()){
              chatClient2.sendate(scanner.nextLine());
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啊呦,不错

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值