netty 群推(Netty实现简单群聊)
netty 群推(Netty实现简单群聊)
2024-06-11 06:04:25  作者:端暧尘手  网址:https://m.xinb2b.cn/life/lwa421899.html

github地址:https://github/saseke/eos-netty

netty 群推(Netty实现简单群聊)(1)

Server端

EosServer.java

package com.songmengyuan.eos.server;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.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;import java.text.SimpleDateFormat;public class EosServer {private int port;private SimpleDateFormat sdf;public EosServer(int port) {this.port = port;}public void start() throws Exception {// boss设置1个EventLoopEventLoopGroup boss = new NioEventLoopGroup(1);EventLoopGroup workers = new NioEventLoopGroup();// 设置启动引导try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(boss, workers).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast("decoder", new StringDecoder());pipeline.addLast("encoder", new StringEncoder());pipeline.addLast("serviceHandler", new EosServerServiceHandler());}});// 绑定端口ChannelFuture channelFuture = serverBootstrap.bind(port).sync();System.out.println("服务器启动");channelFuture.channel().closeFuture().sync();}finally {boss.shutdownGracefully();workers.shutdownGracefully();}}}

EosServerServiceHandler.java

package com.songmengyuan.eos.server;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;public class EosServerServiceHandler extends SimpleChannelInboundHandler<String> {// 用channelGroup来维护所有注册的channelprivate static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd-hh:mm:ss");@Overridepublic void handlerAdded(ChannelHandlerContext ctx) {Channel channel = ctx.channel();String msg = sdf.format(new Date()) " 用户 : " channel.remoteAddress() " 上线\n";System.out.println(msg);// 发送给其他用户channelGroup.writeAndFlush(msg);// 将当前的channel加入channelGroup中channelGroup.add(channel);}// 自动会把当前的channel从group中移除@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) {Channel channel = ctx.channel();String msg = sdf.format(new Date()) " 用户: " channel.remoteAddress() " 下线\n";channelGroup.writeAndFlush(msg);}@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) {Channel channel = ctx.channel();String message = "用户: " channel.remoteAddress() " 发送了: " msg;System.out.println(message);// 发送给除自己之外的其他用户channelGroup.forEach(c -> {if (c == channel) { // 如果当前channel是自己的话String s = sdf.format(new Date()) "[自己] :" msg;c.writeAndFlush(s);}else {c.writeAndFlush(message);}});}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();}}

EosServerBootstrap.java

package com.songmengyuan.eos.server;public class EosServerBootstrap {public static void main(String[] args) throws Exception {EosServer server = new EosServer(9000);server.start();}}

Client端

EosClient.java

package com.songmengyuan.eos.client;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;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;public class EosClient { private final String host; private final int port; public EosClient(String host, int port) { this.host = host; this.port = port; } public void start() throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); try { bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); pipeline.addLast("clientService", new EosClientServiceHandler()); } }); ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); System.out.println("登陆成功"); // 将用户输入的信息写入channel中 Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String msg = scanner.nextLine(); channelFuture.channel().writeAndFlush(msg); } } finally { group.shutdownGracefully(); } }}

EosClientServiceHandler.java

package com.songmengyuan.eos.client;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;public class EosClientServiceHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println(msg); }}

EosClientBootstrap.java

package com.songmengyuan.eos.client;public class EosClientBootstrap { public static void main(String[] args) throws InterruptedException { EosClient client = new EosClient("127.0.0.1",9000); client.start(); }}

  • 会计面试经常问的问题及答案(会计100道经典面试题)
  • 2024-06-11会计100道经典面试题问题:假如我们聘用你,但有时需要做些倒茶端水的杂务,你会反对吗?  回答:“只要需要,我不会斤斤计较”“如果有客人到我所在的那个部门,我会主动倒茶端水,这些杂务只是我的工作内容的一小部分而已”  点评。
  • 为什么有的人总喜欢让别人请吃饭(别人请吃饭聪明人会做到)
  • 2024-06-11别人请吃饭聪明人会做到中国人喜欢在饭桌上相互联系,无论是亲戚朋友还是公司同事吃饭,看似是一件很平常的事情,但从一个人的成长经历,包括性格都能通过吃饭看出来别人请你吃饭时,不要做这些令人讨厌的事情第一件事情,不要邀请自己以外。
  • 张家口怎么去北京首都机场(北京张家口往返新便利)
  • 2024-06-11北京张家口往返新便利为服务市民当下越来越火热的冰雪活动参与热情,记者2月17日获悉,支付宝APP在首页“出行”栏目上线了连接北京、张家口的“冰雪行”服务以热门冰雪活动所在场馆为出行目的地,北京、张家口及周边的市民、游客可。
  • 邪王丑妃小说(邪王戏丑妃)
  • 2024-06-11邪王戏丑妃大婚之夜,新婚夫君与出身青楼的“红颜知己”在婚床上被翻红浪翻云覆雨,她在洞房被迫听了一夜,横眉冷笑,“王爷,是要人还是要休书?”一场意外,她褪去丑陋外衣,露出绝世容颜,她医术惊天,倾国倾城,惹来众多男。
  • 武夷岩茶夏茶(武夷岩茶-高山茶)
  • 2024-06-11武夷岩茶-高山茶大自然赋予武夷山高山生态茶园的自然环境,可谓“得天独厚”,这里的地力丰沛,含有大量的有机质,原生态环境优良,极其适宜茶树生长此处所产制的岩茶品质独特,别有风味,并独具“高山气息”“高山茶”范意:“高山。
  • 不羁放荡爱自由的意思(不羁放荡爱自由是什么意思)
  • 2024-06-11不羁放荡爱自由是什么意思“不羁放纵爱自由”的意思说一个追逐梦想的人,有一颗浪子般流浪的心,天生爱自由,任性而不安分向着前方,永不停步“不羁放纵爱自由”这句话来自歌曲《海阔天空》里,《海阔天空》是香港摇滚乐队Beyond演唱的。
  • 让我们一起来看看海洋生物(海洋梦在这里起航)
  • 2024-06-11海洋梦在这里起航相信每个孩子都曾做过这样一个梦———乘着小船漂流于浩瀚的大海上,仰望灿烂星空,倾听鱼儿秘语这样的美梦不一定能成真,但和千姿百态的海洋生物亲密接触,窥探浩瀚大海的奥秘所在却并不难在美丽的琴岛之上,厦门海。
  • 瑜伽的三种后弯体式(如何在瑜伽中舒适地做金刚体式)
  • 2024-06-11如何在瑜伽中舒适地做金刚体式金刚体式是一种简单的瑜伽体式,它实际上被认为是一种坐姿,这意味着你可以在呼吸或冥想时长时间保持这个姿势是一种坐姿,这意味着你可以在呼吸或冥想时长时间保持这个姿势在这个姿势中,你以跪姿开始,然后双腿向后。
  • 窠巢怎么读(窠巢造句)
  • 2024-06-11窠巢造句“窠巢”读音是:[kēcháo]释义:昆虫、鸟兽的巢穴;借指人安居或聚会的处所;古同“颗”;指文章所依据的老套子,陈旧的格调;古同“棵”“窠巢”造句:⑴飘泊的歌儿从我心中飞去在你爱的呼声里寻找窠巢⑵在。
  • 小k红毯短裤(小K勒头皮造型一言难尽)
  • 2024-06-11小K勒头皮造型一言难尽3月5日,“小K”克里斯汀·斯图尔特和“塞皇”查理兹塞隆的一组合影曝光两人出席的是第37届圣塔芭芭拉国际电影节,小K是获奖者,女神塞隆亲自为她颁奖两位女神曾经在奇幻电影《白雪公主与猎人》中合作,小K饰。
  • 三星g7108v的手机参数(三星g7108和g7108v有什么区别)
  • 2024-06-11三星g7108和g7108v有什么区别三星g7108v的手机参数?若您想要了解G7108V的规格参数,请参考以下介绍:屏幕尺寸:25英寸;分辨率:280x720(HD);材质:TFT触摸屏,下面我们就来看看三星g7108v的手机参数?我们。