netty 群推(Netty实现简单群聊)
netty 群推(Netty实现简单群聊)
2024-09-29 09:01:57  作者:端暧尘手  网址:https://m.xinb2b.cn/tech/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-09-29上海内环最大生态公园上海内环最大生态公园,浦东的春游圣地,门票只要十块钱!说起我国最为繁华的地带,上海绝对是称得上有名的,这个被赋予“经济中心”的城市已经被称为“魔都”近年来上海涌入的城市人口越来越多,仿佛来到大城市打拼。
  • 男宝宝泌尿处一条印子(男宝宝1岁后这个地方还)
  • 2024-09-29男宝宝1岁后这个地方还天气热起来了,李女士每天晚上都会给2岁的儿子洗澡可是,周二晚上给宝宝洗完澡之后,当晚,李女士和丈夫翻来覆去几乎一夜没睡!原来,晚上给孩子洗澡时,李女士无意中碰到了宝宝的阴囊,但是却发现儿子的阴囊瘪瘪的。
  • 乐坛现在的一哥(乐坛第一排面再见了)
  • 2024-09-29乐坛第一排面再见了那个被称为“香港乐坛教父”的男人,走了上海滩:叶丽仪-叶丽仪五十周年据多家媒体报道,著名作曲家、香港流行乐泰斗顾嘉辉于加拿大当地时间1月3日去世,享年92岁消息一出,无数听着港乐长大的人错愕,茫然:一。
  • 木耳泡发后会产生哪种毒素(木耳泡发多久后会产生毒素)
  • 2024-09-29木耳泡发多久后会产生毒素来源:养身中国编辑:史文君责编:王玉珏版权归作者所有,如有侵权,请与我们联系(联系电话:0931-8569680)为什么说“香蕉通便”是假的?今起可填报!家有宝宝的看过来为什么出现大量无症状感染者?张。
  • 空调移机是不是就要加氟(空调移机需要加氟吗)
  • 2024-09-29空调移机需要加氟吗生活当中常常听到“空调移机就必须加氟”的说法,外行人不懂只能是移机师傅说什么听什么,无法判断这个说法的正确与否基本上移机之后,60%的家电维修师傅都会要求你对空调加氟,那么真的有必要吗?移机只是本金,。
  • 给宝宝剪指甲这些小技巧妈咪必学 宝宝剪指甲也是一门技术活
  • 2024-09-29给宝宝剪指甲这些小技巧妈咪必学 宝宝剪指甲也是一门技术活宝宝的身体娇嫩,在日常护理上自然需要父母们更加用心,那些看起来是很简单的生活细节,父母们却不能对此掉以轻心比如说,给宝宝剪指甲这件“小事”,养过娃的宝妈都知道,给宝宝剪指甲可是一个技术活,一不小心就有。
  • 伊瓜苏大瀑布最佳观赏地(雨中的伊瓜苏瀑布)
  • 2024-09-29雨中的伊瓜苏瀑布据报道,由于降雨量激增,巴西和阿根廷交界处的伊瓜苏瀑布的水流量较往日明显增大这是10月12日在巴西南部巴拉那州拍摄的雨中的伊瓜苏瀑布新华社/法新10月12日,游客在巴西南部巴拉那州观赏雨中的伊瓜苏瀑布。
  • 高速公路最新收费信息(关注全新高速公路收费标准来啦)
  • 2024-09-29关注全新高速公路收费标准来啦微信搜索“北青社区报房山版”,点击“关注公众号”,实时接收本报讯息元旦马上就要到啦大家有没有计划好出行游玩呢?带给大家一个好消息北京高速公路全新收费标准将从元旦起执行快来看看有什么变化吧!12月10日。
  • 小狗突然发狂怕人不让碰(胆小狗狗讨食失败)
  • 2024-09-29胆小狗狗讨食失败有时候,性格会决定一个生命的未来,若想改变性格,或许得有一个契机有的狗狗之所以受欢迎,不只是因为长得乖巧可爱,还因为它们的性格十分惹人爱,大家都想将其带回家中好生陪伴而有的狗狗之所以不受欢迎,不只是因。
  • 境由心生世上本无事庸人自扰之(天下本无事庸人自扰之)
  • 2024-09-29天下本无事庸人自扰之去其害马者而已矣黄帝要去具茨山拜见大隗,由方明驾车,昌宇陪乘,张若、謵朋在马前引导,昆阍、滑稽在车后跟随;来到襄城郊外,七位圣人都迷失了方向,没有人可以问路正好遇见牧马的童子,就向他问路说:“你知道具。