网络i/o编程模型16netty框架实现的群聊系统(代码片段)

健康平安的活着 健康平安的活着     2023-03-12     801

关键词:

一 背景描述

1.编写一下群聊系统:实现服务器端和客户端之间数据通讯(非阻塞模式)

服务端: 可以检测用户上线,离线,并实现消息转发功能。

客户端:通过channel可以无阻塞发送消息给其他所用用户,同时可以接受其他用户发送的消息(有服务器转发得到)

2.采用思路:使用netty的非阻塞网络机制

二 代码实现

2.1 服务端代码

1.server

package com.ljf.netty.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @ClassName: NettyGroupchatServer
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/06/03 17:46:02
 * @Version: V1.0
 **/
public class NettyGroupchatServer 

    //监听端口
    private   int port;

    public NettyGroupchatServer(int port) 
        this.port = port;
    
    //处理客户端的请求
    public  void  dealHandler()
        //创建两个线程组
        EventLoopGroup bossGroup=new NioEventLoopGroup(1);
        EventLoopGroup workerGroup=new NioEventLoopGroup();//8个NioEventLoop
        try 
        ServerBootstrap b=new ServerBootstrap();
        b.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() 
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception 
                        //获取到pipeline
                        ChannelPipeline pipeline=ch.pipeline();
                        //向pipeline加入解码器
                        pipeline.addLast("decoder",new StringDecoder());
                        //向peipeline加入编码器
                        pipeline.addLast("encoder",new StringEncoder());
                        //加入自己的业务处理handler
                        pipeline.addLast(new NettyGroupchatServerHandler());
                    
                );
            System.out.println("netty 服务器启动成功!!!");
        ChannelFuture channelFuture = b.bind(port).sync();
        //监听关闭
        channelFuture.channel().closeFuture().sync();
         catch (InterruptedException e) 
            e.printStackTrace();
        
        finally 
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        
    

    public static void main(String[] args) 
        new NettyGroupchatServer(6666).dealHandler();
    

2.自定义服务端

package com.ljf.netty.netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;


import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: NettyGroupchatServerHandler
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/06/03 18:31:21
 * @Version: V1.0
 **/
public class NettyGroupchatServerHandler extends SimpleChannelInboundHandler<String> 
    //定义一个channel组,管理所有的channel,GlobalEventExecutor.INSTANCE是全局的事件执行器,是一个单例
    private static ChannelGroup channelGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //时间格式化器
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     //建立连接连接,将当前channel加入到channelGroup
    public void handlerAdded(ChannelHandlerContext ctx)
        Channel channel=ctx.channel();
        channelGroup.writeAndFlush(" 【客户端:】"+channel.remoteAddress()+" 进入聊天"+sdf.format(new Date())+"\\n");
        channelGroup.add(channel);
    
    //断开连接,将xx客户离开信息推送给当前在线客户

    public   void handlerRemoved(ChannelHandlerContext ctx)
        Channel channel=ctx.channel();
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+" 离开了");
        System.out.println("");
        System.out.println("channelGroup size"+channelGroup.size());
    
     //表示channel处于活动状态,提示xx上线
    public  void channelActive(ChannelHandlerContext ctx)
        System.out.println(""+ctx.channel().remoteAddress()+" 上线了~~~~");
    
    //表示channel处于不活动状态,提示xx离线了
    public void channelInactive(ChannelHandlerContext cxt)
     System.out.println(""+cxt.channel().remoteAddress()+" 离线了~~~~~");
    
   //读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception 
       //获取当前的channel
        Channel channel=ctx.channel();
        //这时我们遍历channelGroup,根据不同情况,回送不同的消息
        channelGroup.forEach(ch ->
            if(channel!=ch)//不是当前的chennel,转发消息
                ch.writeAndFlush(" 【客户】"+channel.remoteAddress()+" 发送了消息:["+s+"] \\n");
            else//回显自己发送的消息给自己
                ch.writeAndFlush("[自己] 发送了消息:"+s+"\\n");
            
        );
    
    //异常处理
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause)
        //关闭通道
        ctx.close();
    

2.2 客户端代码

1.客户端

package com.ljf.netty.netty.groupchat;

import com.ljf.netty.netty.tcp.NettyTcpClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @ClassName: NettyGroupchatClient
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/06/03 19:05:28
 * @Version: V1.0
 **/
public class NettyGroupchatClient 
    //属性
    private final String host;
    private  final int port;

    public NettyGroupchatClient(String host, int port) 
        this.host = host;
        this.port = port;
    
    public void runDeal()
        EventLoopGroup group=new NioEventLoopGroup();
        try 
        Bootstrap bootstrap=new Bootstrap();
        //设置相关参数
        bootstrap.group(group) //设置线程组
                .channel(NioSocketChannel.class) //设置客户端通道的实现类(反射)
                .handler(new ChannelInitializer<SocketChannel>() 
                    protected void initChannel(SocketChannel ch)
                      ChannelPipeline pipeline= ch.pipeline();
                        pipeline.addLast("decoder",new StringDecoder());
                        pipeline.addLast("encoder",new StringEncoder());
                        pipeline.addLast(new NettyGroupchatClientHandler());//加入自己的处理器
                    
                );
        System.out.println("客户端 is ok.....");
        //启动客户端去链接服务器端,channelfuture,涉及道netty的异步模型
            ChannelFuture channelFuture=bootstrap.connect(host,port).sync();
         //得到channel
            Channel channel=channelFuture.channel();
            System.out.println("------"+channel.localAddress()+"------");
            //客户端需要输入信息,创建一个扫描器
            Scanner scanner=new Scanner(System.in);
            while(scanner.hasNextLine())
                String msg=scanner.nextLine();
                //通过channel发送到服务器端
                channel.writeAndFlush(msg+"\\r\\n");
            

         catch (InterruptedException e) 
            e.printStackTrace();
        
        finally 
            group.shutdownGracefully();
        

    

    public static void main(String[] args) 
        new NettyGroupchatClient("127.0.0.1",6666).runDeal();
    

2.客户端自定义处理

package com.ljf.netty.netty.groupchat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @ClassName: NettyGroupchatClientHandler
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/06/03 19:17:46
 * @Version: V1.0
 **/
public class NettyGroupchatClientHandler extends SimpleChannelInboundHandler<String> 
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception 
        System.out.println("客户单 handler发送的消息s:"+s.trim());
    

2.3 调式演示结果

1.启动服务端

2.启动客户端1,并发送信息

3.启动客户端2,并发送信息

 4.下线一个客户端

1.客户端1下线

2.服务端信息

 3.客户端2

网络i/o编程模型10netty介绍

...一个java开源框架。2.netty是一个异步的、基于事件驱动的网络应用框架,用以快速开发高性能、高可靠性的网络IO程序。3.netty主要针对在TCP协议下,面向clients端的高并发应用,或者Peer-to-peer场景下的大量数据持续传输... 查看详情

手动搭建i/o网络通信框架2:bio编程模型实现群聊(代码片段)

第一章:手动搭建I/O网络通信框架1:Socket和ServerSocket入门实战,实现单聊  在第一章中运用Socket和ServerSocket简单的实现了网络通信。这一章,利用BIO编程模型进行升级改造,实现群聊聊天室。    如图:当一个客户端请... 查看详情

网络i/o编程模型24基于netty编写rpc通信框架

一RPC协议1.1RPC协议RPC:remote procedure  call:远程过程调用,是一个计算机通信协议。允许一台机器程序调用另外一台机器的应用。用户无需关心细节,调用本地方法一样的调用远程方法。常见的RPC框架:阿里... 查看详情

网络i/o编程模型18netty通过websocket实现服务,客户端通信(代码片段)

一需求描述基于websocket的全双工的长连接,实现客户端和服务端之间信息的交互。比如客户端浏览器和服务器会相互感知,比如服务器关闭了,浏览器会感知;同样浏览器关闭了,服务器也会感知。二代码实... 查看详情

网络i/o编程模型22netty的源码总结

一netty启动流程1.newNioEventLoopGroup(1):这个表示bossGroup事件组有1个线程可以指定,如果newNioEventLoopGroup()则默认会有cpu核数*2个线程,这样可以充分利用多核的优势。DEFAULT_EVENT_LOOP_THREADS=Math.max(1,SystemPropertyUtil.getInt(&# 查看详情

网络i/o编程模型25大结局netty学习总结

一说明资源说明:1.学习笔记代码https://gitee.com/jurf-liu/io-netty-demo.git2.学习资料参考:尚硅谷Netty视频教程(B站超火,好评如潮)_哔哩哔哩_bilibili 查看详情

网络i/o编程模型19netty的编码与解码

一编码与解码1、数据在网络中传输的都是二进制字节码数据,在发送数据时就需要编码,接收数据时就需要解码。encoder负责把业务数据转成字节码数据,decoder负责把字节码数据转成业务数据。2.netty常见的解码和编... 查看详情

网络i/o编程模型14netty的http协议服务器(代码片段)

一案例1.1案例描述1.netty服务器使用6666端口监听,浏览器发送的请求:http://localhost:6666/2.服务器收到消息后,向浏览器发送消息“hello,我是服务器,你在干什么!!!”,并对特定资源进行过滤。1.2... 查看详情

网络编程笔记linux系统常见的网络编程i/o模型简述

1.典型的I/O模型根据”UnixNetworkProgrammingVolume1”一书第6.2节的说明,Linux系统支持的典型I/O模型包含下面5种:阻塞I/O(blockingI/O)非阻塞I/O(nonblockingI/O)I/O多路复用(I/Omultiplexing,e.g.selec 查看详情

4.基于nio的群聊系统(代码片段)

...法;【1】群聊需求1)编写一个NIO群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)2)实现多人群聊;3)服务器端:可以监测用户上线, 查看详情

网络i/o编程模型11netty常用的3种线程模型

一常用的线程模型1.1传统阻塞I/O服务模型1.特点:采用阻塞IO模式获取输入的数据;每个连接都需要独立的线程完成数据的输入,业务处理数据返回。2.问题:当并发数很大时候,就会常见大量的线程,占用... 查看详情

网络i/o编程模型23netty的出站与入站中handler加载与执行顺序

一出站与入站中handler加载与执行顺序1.1关系梳理1.调用newContext(group,filterName(name,handler),handler)方法,创建一个Context。从这里可以看出来,每次添加一个handler都会常见一个关联的Context。调用addLast方法,将Context追加到... 查看详情

网络i/o编程模型7nio实现聊天室(代码片段)

一nio实现聊天室1.1功能描述服务器端:可以检测用户上线、离线,并实现消息的转发功能。客户端:通过channel可以五阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)... 查看详情

走进网络编程与netty

网络编程与Netty(一)计算机网络基础部分计算机网络体系OSI七层模型​开放系统互连参考模型(OpenSystemInterconnect简称OSI)是国际标准化组织(ISO)和国际电报电话咨询委员会(CCITT)联合制定的开放系统互连参考模型,为开放式... 查看详情

网络编程模型(i/o模型)

首先了解什么是同步(synchronous),异步(asynchronous),阻塞(blocking),非阻塞(nonblocking):同步与异步同步和异步是基于应用程序与操作系统处理I/O所采用的方式同步:是应用程序直接参与I/O读写的操作,么有完毕将会等待... 查看详情

java开发必备!i/o与netty原理精讲(建议收藏)

...原理,并介绍当前流行框架Netty的基本原理。一JavaI/O模型1BIO(BlockingIO)BIO是同步阻塞模型, 查看详情

一文读懂高性能网络编程中的i/o模型

...的服务端架构模式已经无能为力。本文(和下篇《高性能网络编程(六):一文读懂高性能网络编程中的线程模型》)旨在为大家提供有用的高性能网络编程的I/O模型概览以及网络服务进程模型的比较,以揭开设计和实现高性能网... 查看详情

day858.高性能网络应用框架netty-java并发编程实战(代码片段)

高性能网络应用框架NettyHi,我是阿昌,今天学习记录的是关于高性能网络应用框架Netty的内容。Netty是一个高性能网络应用框架,应用非常普遍,目前在Java领域里,Netty基本上成为网络程序的标配了。Netty框架... 查看详情