netty 群推(Netty实现简单群聊)
netty 群推(Netty实现简单群聊)
2024-06-01 10:23:33  作者:端暧尘手  网址:https://m.xinb2b.cn/sport/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(); }}

  • 小向日葵种植方法(向日葵种植养护方法是什么)
  • 2024-06-02向日葵种植养护方法是什么土壤:向日葵对于土壤的并无太高的要求,因为它的生长能力很好不过,使用排水性能好、含有腐殖质的土最佳,最好还施加些基肥光照:它在生长开花的过程中,是一定要接受光照的,最好是在向阳处养殖若是盆栽养殖的话,。
  • 生日祝福语随意一点(真挚生日祝福语)
  • 2024-06-02真挚生日祝福语1、岁岁年年,岁月又一重,每一年的这一天,是最开心的一天,因为这一天是你的生日,我要和你分享这快乐,并送给你最诚挚的祝福,祝你生日快乐,天天快乐!2、春风暖不暖,大雁先知道花儿美不美,蝴蝶先知道草原大。
  • 解决失眠的8个办法总有一款适合你(对抗失眠的经验)
  • 2024-06-02对抗失眠的经验对抗失眠的经验(介绍一个行之有效的办法)我是一个老失眠了不过失眠之后,到目前为止,靠自我调理都还能纠正我最长失眠的阶段还是高中大学的阶段,后来即使失眠,我也通常都不会丧失睡眠的信心说一下最近一个月我的。
  • wps随机公式有哪些
  • 2024-06-02wps随机公式有哪些wps表格公式大全1、数学与三角函数ABS返回数字的绝对值ACOS返回数字的反余弦值ACOSH返回数字的反双曲余弦值。
  • 舆情监测与危机公关(舆情公关什么叫做舆情)
  • 2024-06-02舆情公关什么叫做舆情文丨公关之家作者:不承权舆引言:对于企业的品牌公关来说,舆情是非常常见而又重要的一个概念,舆情监控也是其公关的重要方面之一舆情是什么意思舆情是“舆论情况”的简称,而舆论是指在一定的社会空间内,围绕某一。
  • 巴西龟最佳冬眠方法(养殖巴西龟怎么冬眠)
  • 2024-06-02养殖巴西龟怎么冬眠最简单的办法是把龟移到室内阴暗安静处,浅水即水刚盖过龟甲背,每月换水一次,除了换水尽量不去打扰它注意冬眠温度0——10度最适宜这样乌龟不太活动,减少体内消耗最好能每天晒会太阳大龟也可以用湿润的沙子帮忙。
  • TPE考试6月再次开放(TPE考试6月再次开放)
  • 2024-06-02TPE考试6月再次开放法国高等教育署全年在全国六个中心组织预签证法语考试目前大多数中心仍然开放(广州、武汉、成都、沈阳),并组织考试但是官方强烈建议我们优先考虑前往这些中心参加考试最新场次TPE在线考试对于那些无法前往以上。
  • 内分泌失调怎么来调理(内分泌失调怎么调理)
  • 2024-06-02内分泌失调怎么调理一旦女性内分泌出现紊乱,那么就会让皮肤变得越来越差、月经不调甚至会让女性出现不孕的情况,那如何调节好内分泌呢怎么调节内分泌?试试这几种小妙招!1、有氧运动每周至少有三次有氧运动,每次要达到30分钟,这。
  • 春节的习俗有哪些写成几句话(春节的习俗有哪些)
  • 2024-06-02春节的习俗有哪些#红红火火过大年#春节是中国民间最隆重盛大的传统节日,有买年货、扫尘、贴对联、吃年夜饭、守岁、拜岁、拜年、舞龙舞狮、拜神祭祖、祈福攘灾、放鞭炮、放烟花、游神、押舟、庙会、游锣鼓、游标旗、上灯酒、赏花灯。
  • 世界最漂亮的飞鸟是谁(世界最美飞鸟)
  • 2024-06-02世界最美飞鸟朋友你会不会也常常有一种感觉,大自然的一切美妙得令人惊讶!一切的山河树木、花鸟鱼虫,都美得不可思议让人不禁思想:它们从哪里来?谁创造了它们?但这又实在是一个千古谜题棕煌蜂鸟,身长8厘米,毛色棕红,喉部。
  • 顶级演员谢苗现状(知名童星谢苗近况)
  • 2024-06-02知名童星谢苗近况5月13日,38岁知名童星谢苗在个人社交账号上分享了一段视频,曝光了自己的近况他配文称,努力的意义,不在于会让你取得多大成就,只是让你在平凡的日子里,活得比原来的那个自己更好一点,用最好的状态迎接新的。