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

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


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(); }}

  • 推荐经典仙侠小说(5本经典仙侠后宫小说)
  • 2024-11-085本经典仙侠后宫小说大家好,我是小马哥,今天推荐5本经典仙侠后宫小说,不同境界的美女都各有特色,值得细品一二第一本:《问道红尘》作者:姬叉书评:主角穿越到仙侠世界,正巧遇到原身被人夺舍,无意中插队抢下身体,带着夺舍失败的。
  • 苏州住宅成交70套 苏州9月28日成交住宅263套
  • 2024-11-08苏州住宅成交70套 苏州9月28日成交住宅263套苏州搜房网讯:据苏州住建局网站最近数据显示:9月28日苏州商品房成交312套(其中住宅263套,非住宅49套),成交面积34338.7㎡[9月28日住宅类签约套数:263套环比减少62套9月28日苏州。
  • g10绥满高速封路(注意G10绥满高速K428500-K430)
  • 2024-11-08注意G10绥满高速K428500-K430原标题:注意!G10绥满高速K428500-K430480路段进行半幅封闭半幅道路双向混流通行东北网4月22日讯(记者葛金鑫)为确保国家百大工程吉黑高速山河(吉林省界)至哈尔滨(永源镇)段工程项目顺利。
  • 榴莲壳吃完可以做什么东西(变废为宝来煲汤)
  • 2024-11-08变废为宝来煲汤闻起来臭臭的榴莲其实非常营养,但很多人吃榴莲时顺手就把壳扔了,是啊,谁能想到榴莲壳是个宝贝呢!用它来煲汤有惊人的功效榴莲壳白色部分煲汤补虚益气滋阴降火用榴莲壳来煲汤,即使在饮遍百汤的广东人看来也是。
  • 王者荣耀阿轲怎样玩才厉害(王者荣耀阿轲攻略)
  • 2024-11-08王者荣耀阿轲攻略印象中的阿轲是王者荣耀中最具代表性的刺客英雄,是将暴力输出和飘逸打法结合得最完美的那一个上上个版本的阿轲,小编只喜欢极限输出的暴力出装但在上个版本,迫于版本大势,不得不转为主流的半肉输出装好在经过最近。
  • 传播营销最佳广告(易美传播林炜琪)
  • 2024-11-08易美传播林炜琪10月19日,由母婴行业观察主办的“2019母婴媒介大会”在上海召开,众多甲方、资源方齐聚现场,分享最精准丰富的资源、最具代表性的案例、最新潮的媒介玩法,旨在提升母婴企业两端对接效率,让行业价值密度最。
  • moschino卫衣怎么辨别真伪(moschino莫斯奇诺小熊t恤真假)
  • 2024-11-08moschino莫斯奇诺小熊t恤真假大家对MOSCHINO家的小熊t恤应该都不陌生,已经算是一大爆款了,这款t恤现在很多代购都在造假,所以我们在购买的时候要很注意,我们一起来学学moschino小熊t恤真假的辨认方法吧莫斯奇诺小熊t恤真。
  • 斗罗大陆极致武魂有哪些(那些强大的极致武魂魂师)
  • 2024-11-08那些强大的极致武魂魂师斗罗大陆武魂千千万,可是极致的武魂却非常稀少,而且拥有极致武魂的魂师修炼都非常困难,但是每一位极致武魂的魂师都是非常强大的魂师,而且天赋也是非常强大的,下面就让队长带大家来看看那些极致武魂的魂师吧!极。
  • 感觉整个人都要疯掉(满脑子都是玻璃的样子)
  • 2024-11-08满脑子都是玻璃的样子美轮美奂的玻璃~文章来源:生生景观ID:sheng_design1作者:生生君编辑:亦夕设计中材质千万种,一种材质,一场秀“玻璃”在设计中形态百出,也是设计们的宠爱,一块看起来易碎的材质,还有后患看看。
  • 郎咸平事件中空姐后来怎样了(郎咸平手撕空姐全过程)
  • 2024-11-08郎咸平手撕空姐全过程郎教授在与第六任妻子的婚姻存续期间给婚外异性女友以及其父亲各送了一套,但在感情转淡后,郎教授想把房子收回来经过两次开庭后终于如愿以偿,最后空姐出身的女友不仅什么都没得到,最后还莫名为郎教授背上了900。