网络编程之NIO聊天室

1.创建Nio服务端

package nio.study;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
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.util.Iterator;
import java.util.Set;

import javax.xml.ws.handler.MessageContext.Scope;

/**
 *创建Nio服务端 
 */
public class NIOServer {
    /**
     *启动 
     * @throws IOException 
     */
    public void start() throws IOException {
        /**
         * 1、 创建selector
         */
        Selector selector = Selector.open();
        
        /**
         * 2、通过ServerScoketChannel创建channel通过 
         */
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        
        /**
         * 3、为channel通道绑定监听端口 
         */
        serverSocketChannel.bind(new InetSocketAddress(8000));
        /**
         * 4、**设置channel为非阻塞状态 
         */
        serverSocketChannel.configureBlocking(false);
        
        
        /**
         * 5、将channel注册到selector上 监听连接事件
         */
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务器启动成功!");
        /**
         * 6、循环等待新接入的连接 
         */
        for(;;) {
            /**
             * TODO 获取可用channel数量
             */
            int readyChannels = selector.select();
            /**
             * TODO 为什么这样?
             */
            if(readyChannels == 0) continue;
            /**
             *获取channel可用集合 
             */
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectedKeys.iterator();
            while(iterator.hasNext()) {
                /**
                 *selectrionKey实例 
                 */
                SelectionKey selectionKey = iterator.next();
                /**
                 *移除Set中的当前selectionKey 
                 */
                iterator.remove();
                /**
                 * 7、根据就绪状态,调用对应方法处理业务逻辑 
                 */
                /**
                 *如果是接入事件 
                 */
                if(selectionKey.isAcceptable()) {
                    acceptHandler(serverSocketChannel, selector);
                }
                /**
                 *如果是可读事件 
                 */
                if(selectionKey.isReadable()) {
                    readHandler(selectionKey, selector);
                }
            }
            
        }
    }
    /**
     *接入事件处理 
     * @throws IOException 
     */
    private void acceptHandler(ServerSocketChannel serverSocketChannel,Selector selector) 
            throws IOException {
        /**
         *如果是接入事件,创建socketChannel 
         */
        SocketChannel socketChannel = serverSocketChannel.accept();
        /**
         *将socketChannel设置为非阻塞工作模式 
         */
        socketChannel.configureBlocking(false);
        /**
         *将channel注册到selector上,监听可读事件 
         */
        socketChannel.register(selector, SelectionKey.OP_READ);
        /**
         * 回写客户端提示信息
         */
        socketChannel.write(Charset.forName("UTF-8").
                encode("你与聊天室的其他人都不是朋友关系,请注意隐私安全"));
    }
    /**
     *可读事件处理 
     * @throws IOException 
     */
    private void readHandler(SelectionKey selectionKey,Selector selector) throws IOException {
        /**
         *要从 selectionKey中获取已经就绪的channe 
         *SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
         */
        SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
         /**
          * 创建Buffer
          */
         ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
         /**
          *循环读取客户端信息 
          */
         String request = "";
         while(socketChannel.read(byteBuffer)>0) {
             /**
              *切换buffer为读模式 
              */
             byteBuffer.flip();
             /**
              *读取buffer中的内容 
              */
             request += Charset.forName("UTF-8").decode(byteBuffer);
         }
         /**
          * 再次将socketChannel注册到selector上
          */
         socketChannel.register(selector, SelectionKey.OP_READ);
         /**
          * 将客户端发送的请求信息,广播给其他客户端
          */
         if(request.length() > 0) {
             broadCast(selector, socketChannel, request);
         }
    }
    
    private void broadCast(Selector selector,SocketChannel sourceChannel,String request) {
        /**
         *获取到所有已接入的客户端channel 
         */
        Set<SelectionKey> selectionKeySet = selector.keys();
        /**
         *循环向所有channel广播 
         */
        selectionKeySet.forEach(selectionKey->{
            Channel targetchannel = selectionKey.channel();
            //剔除发消息的客户端
            if(targetchannel instanceof SocketChannel
                    && targetchannel != sourceChannel) {
                try {
                    ((SocketChannel)targetchannel).
                    write(Charset.forName("UTF-8").encode(request));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     *主方法 
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        NIOServer server = new NIOServer();
        server.start();
    }
}

2、创建NIO客户端

package nio.study;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

public class NioClient {
    /**
     *启动 
     * @throws IOException 
     */
    public void start(String nickName) throws IOException {
        /**
         *连接服务器端 
         */
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8000));
        /**
         *接收服务端的响应 
         */
        //新开线程专门接收服务器端的响应数据
        Selector selector = Selector.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        new Thread(new NioClientThreadHandler(selector)).start();;
        
        /**
         *向服务器发送数据
         */
        System.out.println("客户端:");
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()) {
            String request = scanner.nextLine();
            if(request != null && request.length() > 0) {
                socketChannel.write(Charset.forName("UTF-8").encode(nickName+":"+request));
            }
        }
        
    }
    /**
     *主方法 
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
//      new NioClient().start();
    }
}

3、NIO客户端线程处理类

package nio.study;

import java.io.IOException;
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.util.Iterator;
import java.util.Set;

public class NioClientThreadHandler implements Runnable {
    private Selector selector;
    
    public NioClientThreadHandler(Selector selector) {
        super();
        this.selector = selector;
    }

    @Override
    public void run() {
         for(;;) {
             try {
                int readyChannels = selector.select();
            
                if(readyChannels == 0) continue;
                /**
                 *获取channel可用集合 
                 */
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectedKeys.iterator();
                while(iterator.hasNext()) {
                    /**
                     *selectrionKey实例 
                     */
                    SelectionKey selectionKey = iterator.next();
                    /**
                     *移除Set中的当前selectionKey 
                     */
                    iterator.remove();
                     
                    /**
                     *如果是接入事件 
                     */
                    if(selectionKey.isReadable()) {
                        readHandler(selectionKey, selector);
                    }
                    
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
         }
        
    }
    private void readHandler(SelectionKey selectionKey,Selector selector) throws IOException {
        /**
         *要从 selectionKey中获取已经就绪的channe 
         *SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
         */
        SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
         /**
          * 创建Buffer
          */
         ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
         /**
          *循环读取客户端信息 
          */
         String response = "";
         while(socketChannel.read(byteBuffer)>0) {
             /**
              *切换buffer为读模式 
              */
             byteBuffer.flip();
             /**
              *读取buffer中的内容 
              */
             response += Charset.forName("UTF-8").decode(byteBuffer);
         }
         /**
          * 再次将socketChannel注册到selector上
          */
         socketChannel.register(selector, SelectionKey.OP_READ);
         /**
          * 将服务的信息
          */
         if(response.length() > 0) {
             System.out.println(response);
         }
    }

}

4、创建NioClient多个客户端实现聊天

package nio.study;

import java.io.IOException;

public class AClient {
    public static void main(String[] args) throws IOException {
        new NioClient().start("AClient");
    }
}
package nio.study;

import java.io.IOException;

public class BClient {
    public static void main(String[] args) throws IOException {
        new NioClient().start("BClient");
    }
}
package nio.study;

import java.io.IOException;

public class CClient {
    public static void main(String[] args) throws IOException {
        new NioClient().start("CClient");
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容

  • 一、简历准备 1、个人技能 (1)自定义控件、UI设计、常用动画特效 自定义控件 ①为什么要自定义控件? Andr...
    lucas777阅读 5,200评论 2 54
  • Java知识点1、==和equals的区别基本类型比较==比较内容 equals比较地址值引用类型比较==比较地址...
    压抑的内心阅读 592评论 0 0
  • 熟练掌握 BIO,NIO,AIO 的基本概念以及一些常见问题是你准备面试的过程中不可或缺的一部分,另外这些知识点也...
    小王学java阅读 2,073评论 0 0
  • 第11章 - Java NIO 作者:vwFisher时间:2019-09-04GitHub代码:https://...
    vwFisher阅读 422评论 0 2
  • 一 知乎上有人问:读了很多书,但都忘掉了,读书的意义在哪里? 一位网友回:初中的时候,有个同桌总是不喜欢学习,有一...
    芹菜qincai阅读 342评论 1 3