从入门到超神进阶的Netty群聊系统
目录
- 服务端
- 客户端
服务端 服务端一样的需要创建BossGroup 和 WorkGroup , 然后使用ServerBootStrap 来配置Netty和启动Netty。
public class NettyGroupChatServer {public static void main(String[] args) {new NettyGroupChatServer().start(); }//监听public void start(){//循环组NioEventLoopGroup bossGroup = new NioEventLoopGroup(); NioEventLoopGroup workGroup = new NioEventLoopGroup(); //启动引导ServerBootstrap bootstrap = new ServerBootstrap(); //Netty配置bootstrap.group(bossGroup,workGroup).option(ChannelOption.SO_BACKLOG,32).childOption(ChannelOption.SO_KEEPALIVE,true).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() {@Overrideprotected void initChannel(SocketChannel channel) throws Exception {//解码器channel.pipeline().addLast("decoder", new StringDecoder()); //编码器channel.pipeline().addLast("encoder",new StringEncoder()); //处理器channel.pipeline().addLast("nettyGroupChatHandler",new NettyGroupChatServerHandler()); }}); try {//启动服务ChannelFuture future = bootstrap.bind(new InetSocketAddress("127.0.0.1", 8888)).sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) {e.printStackTrace(); }finally {//关闭资源bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); }}}
服务端处理器我们通过继承 SimpleChannelInboundHandler 入站Handler来处理消息。
其中提供了几个方法
- channelRead0 ():读取消息
- handlerRemoved ():客户端断开
- handlerAdded ():客户端建立连接
- exceptionCaught ():出现异常
public class NettyGroupChatServerHandler extends SimpleChannelInboundHandler {//把所有客户端的channel保存起来private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {String message = dateFormat.format(new Date())+":%s:"+msg; //消息转发给所有的客户端channels.forEach(channel -> {if(channel == ctx.channel()){String sendMsg = String.format(message, "我"); channel.writeAndFlush(sendMsg); System.out.println(sendMsg); }else{String sendMsg = String.format(message, ctx.channel().remoteAddress()); channel.writeAndFlush(sendMsg); System.out.println(sendMsg); }}); }//断开连接 , 把消息广播给其他客户端@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) throws Exception {String message = dateFormat.format(new Date())+":"+ctx.channel().remoteAddress()+":断开连接"; channels.writeAndFlush(message); System.out.println(message); }//建立连接@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception {String message = dateFormat.format(new Date())+":"+ctx.channel().remoteAddress()+":加入聊天室"; //自动把消息广播给其客户端channels.writeAndFlush(message); //客户端加入组channels.add(ctx.channel()); System.out.println(message); }//出现异常@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.channel().close(); }//客户端退出@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {String message = dateFormat.format(new Date())+":"+ctx.channel().remoteAddress()+":退出聊天室"; System.out.println(message); }//客户端出于活动@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {String message = dateFormat.format(new Date())+":"+ctx.channel().remoteAddress()+":上线啦"; System.out.println(message); }}
客户端 客户端需要创建一个循环事件组,然后通过BootStrap去启动,然后扫描键盘输入作为数据源来把信息发送给服务端
public class NettyGroupChatClient {public static void main(String[] args) {new NettyGroupChatClient().start(); }public void start(){NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer() {@Overrideprotected void initChannel(SocketChannel channel) throws Exception {//解码器channel.pipeline().addLast("decoder", new StringDecoder()); //编码器channel.pipeline().addLast("encoder",new StringEncoder()); //处理器channel.pipeline().addLast("nettyGroupChatClientHandler",new NettyGroupChatClientHandler()); }}); try {ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8888)).sync(); //通道Channel channel = future.channel(); //扫描键盘输入Scanner scanner = new Scanner(System.in); while(scanner.hasNextLine()){String message = scanner.nextLine(); //发送数据channel.writeAndFlush(message); }} catch (InterruptedException e) {}finally {eventLoopGroup.shutdownGracefully(); }}}
对于处理器只需要接收服务端转发过来的消息即可
public class NettyGroupChatClientHandler extends SimpleChannelInboundHandler {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {System.out.println(msg); }}
启动服务端和多个客户端,效果如下
![从入门到超神进阶的Netty群聊系统](https://img.it610.com/image/info11/a503a41d6ecd47e3879cf0de654c9394.jpg)
文章图片
![从入门到超神进阶的Netty群聊系统](https://img.it610.com/image/info11/9d4d3ee599be4d8b87920546206fad53.jpg)
文章图片
![从入门到超神进阶的Netty群聊系统](https://img.it610.com/image/info11/4fa8e677a8674fd393f1220906c0aecd.jpg)
文章图片
【从入门到超神进阶的Netty群聊系统】到此这篇关于从入门到超神系列的Netty群聊系统的文章就介绍到这了,更多相关Netty群聊系统内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 2018-02-06第三天|2018-02-06第三天 不能再了,反思到位就差改变
- 一个小故事,我的思考。
- Docker应用:容器间通信与Mariadb数据库主从复制
- 第三节|第三节 快乐和幸福(12)
- 你到家了吗
- 一个人的碎碎念
- 遇到一哭二闹三打滚的孩子,怎么办┃山伯教育
- 死结。
- 我从来不做坏事
- 赢在人生六项精进二阶Day3复盘