JAVA-NIO实现聊天室详细代码说明

JAVA-NIO实现聊天室详细代码说明

github源码:https://github.com/JolyouLu/JAVAIO.git

src\main\java\com\JolyouLu\nio\groupchat 文件夹下

public class GroupChatServer {

//定义属性

private Selector selector;

private ServerSocketChannel listenChannel;

private static final int PORT = 6666;

//构造器 完成初始化工作

public GroupChatServer() {

try {

//得到选择器

selector = Selector.open();

//初始化ServerSocketChannel

listenChannel = ServerSocketChannel.open();

//绑定端口

listenChannel.socket().bind(new InetSocketAddress(PORT));

//设置非阻塞模式

listenChannel.configureBlocking(false);

//将来listenChannel注册到Selector

listenChannel.register(selector, SelectionKey.OP_ACCEPT);

}catch (IOException e){

e.printStackTrace();

}

}

//监听

public void listen(){

try {

//循环监听

while (true){

int count = selector.select(2000); //阻塞2秒监听,通道有没有事件发生

if (count > 0){ //返回>0 有事件要处理

//遍历selectedKeys集合

Iterator iterator = selector.selectedKeys().iterator();

while (iterator.hasNext()){

//获取SelectionKey

SelectionKey key = iterator.next();

if (key.isAcceptable()){ //如果通道发生,客户端连接事件

//为连接的客户端,生成socketChannel

SocketChannel socketChannel = listenChannel.accept();

//切换非阻塞模式

socketChannel.configureBlocking(false);

//把socketChannel注册到selector中,并监听读事件

socketChannel.register(selector,SelectionKey.OP_READ);

//提示客户端连接上了

System.out.println(socketChannel.getRemoteAddress() + " 客户端 上线");

}

if (key.isReadable()){//如果通道发生,可读事件

//处理读

readData(key);

}

//清理读取的selectedKeys容器 防止重复处理

iterator.remove();

}

}

}

}catch (Exception e){

e.printStackTrace();

}finally {

}

}

//读取客户端消息

private void readData(SelectionKey key){

//定义一个SocketChannel

SocketChannel channel = null;

try {

//取到关联的channel

channel = (SocketChannel) key.channel();

//创建buffer

ByteBuffer buffer = ByteBuffer.allocate(1024);

int count = channel.read(buffer);

//根据count的值做处理

if (count > 0){ //读取到数据

//把缓冲区的数据转字符串

String msg = new String(buffer.array(), "GBK");

//输出消息

System.out.println("from 客户端:"+ msg);

//向其它客户端转发消息

sendInfoToOtherClients(msg,channel);

}

}catch (IOException e){

try {

System.out.println(channel.getRemoteAddress() + " 离线了..");

//取消注册

key.cancel();

//关闭通道

channel.close();

} catch (IOException ioException) {

ioException.printStackTrace();

}

}

}

//转发消息给其它客户端(channel)

private void sendInfoToOtherClients(String msg,SocketChannel self) throws IOException {

System.out.println("服务器转发消息中...");

//遍历 所有的注册到Selector的SocketChannel排查self

for (SelectionKey key : selector.keys()) {

//取出通道

Channel targetChannel = key.channel();

//targetChanneld的类型是SocketChannel,并且targetChannel不是自己

if (targetChannel instanceof SocketChannel && targetChannel != self){

//转型

SocketChannel dest = (SocketChannel)targetChannel;

//将来msg 存到buffer

ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes("GBK"));

//将来buffer的数据写入通道

dest.write(buffer);

}

}

}

public static void main(String[] args) {

//初始化服务器对象

GroupChatServer chatServer = new GroupChatServer();

chatServer.listen();

}

}

客户端

public class GroupChatClient {

//定义相关属性

private final String HOST = "127.0.0.1"; //服务器IP

private final int PORT = 6666; //服务器端口

private Selector selector;

private SocketChannel socketChannel;

private String username;

//构造器,初始化

public GroupChatClient() {

try {

//得到选择器

selector = Selector.open();

//连接服务

socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));

//设置非阻塞

socketChannel.configureBlocking(false);

//将来socketChannel注册到Selector,关注读事件

socketChannel.register(selector, SelectionKey.OP_READ);

//得到username

username = socketChannel.getLocalAddress().toString().substring(1);

System.out.println(username + " is ok ...");

}catch (Exception e){

e.printStackTrace();

}

}

//向服务器发送消息

public void sendInfo(String info){

info = username + " 说:" + info;

try {

socketChannel.write(ByteBuffer.wrap(info.getBytes("GBK")));

}catch (IOException e){

e.printStackTrace();

}

}

//读取从服务器端回复的消息

public void readInfo(){

try {

int readChannels = selector.select(2000);

if (readChannels > 0){//有可用的通道

Iterator iterator = selector.selectedKeys().iterator();

while (iterator.hasNext()){

SelectionKey key = iterator.next();

if (key.isReadable()){

//得到相关的通道

SocketChannel socketChannel = (SocketChannel) key.channel();

//得到一个Buffer

ByteBuffer buffer = ByteBuffer.allocate(1024);

//buffer 读取通道数据

socketChannel.read(buffer);

//把读到缓冲区的数据转成字符串

String msg = new String(buffer.array());

System.out.println(msg.trim());

}

iterator.remove();

}

}

}catch (IOException e){

e.printStackTrace();

}

}

public static void main(String[] args) {

//启动客户端

GroupChatClient chatClient = new GroupChatClient();

//启动一个线程,每隔开3秒读取服务器发送的数据

new Thread(new Runnable() {

@Override

public void run() {

while (true){

chatClient.readInfo();

try {

Thread.currentThread().sleep(3000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}).start();

//发送数据

Scanner scanner = new Scanner(System.in);

while (scanner.hasNextLine()){

String s = scanner.nextLine();

chatClient.sendInfo(s);

}

}

}

测试

设置启动参数,当前类可以同时运行多个

JAVA-NIO实现聊天室详细代码说明相关教程

java中nio怎么实现聊天,JAVA-NIO实现聊天室详细代码说明相关推荐

  1. java中的jpa_JPA教程–在Java SE环境中设置JPA

    java中的jpa JPA代表Java Persistence API,它基本上是一个规范,描述了一种将数据持久存储到持久存储(通常是数据库)中的方法. 我们可以将其视为类似于Hibernate之类的 ...

  2. Java 位运算理解 Java中的位移运算整理 Java右移n位 Java左移n位

    Java 位运算理解 Java中的位移运算整理 Java右移n位 Java左移n位 一.概述 1.在浏览一篇文章时,看到一个介绍 ,使用位移操作替代乘除法 ,若位移多位该怎么计算呢?  二.代码理解 ...

  3. Java中的字符集编码入门Java中的增补字符

    转载自:http://jiangzhengjun.iteye.com/blog/512083 Java中的字符集编码入门Java中的增补字符 博客分类: 字符集编码 Java Java号称对Unico ...

  4. java中super用来定义父类,Java中super的几种用法及与this的区别

    综观目前的 Web 应用,多数应用都具备任务调度的功能.本文由浅入深介绍了几种任务调度的 Java 实现方法,包括 Timer,Scheduler, Quartz 以及 JCron Tab,并对其优缺 ...

  5. groovy 使用java类_在java中使用groovy怎么搞 (java and groovy)

    什么是groovy? 一种基于Java虚拟机的动态语言,可以和java无缝集成,正是这个特性,很多时候把二者同时使用,把groovy作为java的有效补充.对于Java程序员来说,学习成本几乎为零.同 ...

  6. java中怎样克隆,如何在Java中克隆列表?

    要克隆Java中的列表,最简单的方法是使用ArrayList.clone()方法- 示例import java.util.ArrayList; public class Demo { public s ...

  7. JAVA中一维数组的作用,JAVA中一维数组和二维数组的定义

    在java中数组被看成是一个对象 在定义数组时,有两种定义方法:int[] a 和int a[]:第二种是C/C++对数组定义方式,对于JAVA建议采用第一种定义方式. 总的原则:任何对象在被调用之前 ...

  8. java中char占的二进制,java数据类型与二进制详细介绍

    java数据类型与二进制详细介绍 在java中 Int 类型的变量占 4个字节 Long 类型的变量占8个字节 一个程序就是一个世界,变量是这个程序的基本单位. Java基本数据类型 1. 整数类型 ...

  9. java中的类加载器有,Java自定义的类加载器,java自定义加载,在java中类加载器有以...

    Java自定义的类加载器,java自定义加载,在java中类加载器有以 在java中类加载器有以下几种java虚拟机自带的加载器 1)根类加载器(Bootstrap,c++实现)2)扩展类加载器(Ex ...

最新文章

  1. win8.1怎么安装iis
  2. 【原创翻译】如何命名变量
  3. Qtum量子链应邀出席2019棉兰区块链沙龙进军东南亚市场第一站
  4. 蓝桥杯C++ AB组辅导课 第二讲 二分与前缀和 Acwing
  5. 通过XmlSerializer 实现XML的序列化与反序列化
  6. require(),include(),require_once()和include_once()区别
  7. Spring3:类型安全依赖项注入
  8. 狂妄之人怎么用计算机弹,【B】 Undertale Sans战斗曲 MEGALOVANIA狂妄之人
  9. 使用Tomcat部署应用
  10. Flink 1.11 SQL 十余项革新大揭秘,哪些演变在便捷你的使用体验?
  11. vscode 推荐premiter_自用VSCode优质插件推荐
  12. webserver之处理HTTP请求
  13. left join,right join,inner join,full join之间的区别
  14. html5 简单实例源代码
  15. 直方图均衡化的数学原理
  16. ios系统中的美国App Store出现英文看不懂怎么办?
  17. 《图解网络硬件》网络硬件通用基础知识
  18. 开关稳压集成电路电源
  19. vue项目使用 Recorder.js 实现录音功能
  20. 基础测绘计算函数设计(坐标正反算、交会计算)

热门文章

  1. mfc搜索新建access字段_MFC ODBC类 Access数据库的操作
  2. redis 哨兵 异步_redis 使用历程
  3. yuv格式转换是那个组织定义的_AI 如何赋能摄像机?这场沙龙为你解锁“软件定义”新概念...
  4. 小米登录协议分析_小米回应小米11充电头兼容问题
  5. 2019蓝桥杯国赛B组第九题
  6. 时间序列分析源资料汇总
  7. git 检查更新文件_Git通过差异比对快速打包待更新文件(SQL)
  8. python float 精度_numpy.float128的内部精度是多少?
  9. tp5支持啥数据库_MS Access数据库是被严重低估的一款优秀软件
  10. 设计模式--程序猿必备面向对象设计原则