城市直播房产教育博客汽车
投稿投诉
汽车报价
买车新车
博客专栏
专题精品
教育留学
高考读书
房产家居
彩票视频
直播黑猫
投资微博
城市上海
政务旅游

在springboot项目中集成Netty进行消息发送和接收

2月18日 碧落盟投稿
  概述
  本文通过一个简单的demo来介绍Netty在springboot项目中的使用,其中包括了服务器端和客户端的启动代码,客户端向服务器端发送文本消息。maven依赖dependencygroupIdio。nettygroupIdnettyallartifactIdversion4。1。76。Finalversiondependency关键点服务器端在启动的时候开放一个端口:19080客户端在启动的时候通过ip和端口连上服务器端客户端和服务器端都通过Channel对象向彼此发送数据服务器和客户端都通过继承ChannelInboundHandlerAdapter类实现对消息的读取和回写等操作服务器和客户端都通过StringDecoder和StringEncoder实现对消息的解码和转码操作服务器和客户端启动的时候都会阻塞当前线程,因此需要在一个单独的线程中进行启动消息发送的例子本例是一个springbootweb项目,项目占用了8080端口服务器端在启动的时候开放19080端口(注意不要和web端口冲突了)客户端在启动的时候连上服务器端通过webapi向客户端发送数据,客户端再通过Channel对象向服务器端发送数据服务器接收到客户端数据后也通过Channel对象向客户端发送数据server服务器端通过PostConstruct注解的方法进行启动,具体如下packagecom。ckjava。test。importio。netty。bootstrap。ServerBimportio。netty。channel。ChannelIimportio。netty。channel。ChannelOimportio。netty。channel。EventLoopGimportio。netty。channel。nio。NioEventLoopGimportio。netty。channel。socket。SocketCimportio。netty。channel。socket。nio。NioServerSocketCimportio。netty。handler。codec。string。StringDimportio。netty。handler。codec。string。StringEimportlombok。extern。slf4j。Slf4j;importorg。springframework。stereotype。Cimportjavax。annotation。PostCimportjavax。annotation。PreDimportjava。net。InetSocketAimportjava。util。concurrent。ForkJoinPSlf4jComponentpublicclassHelloWorldServer{privatestaticfinalEventLoopGroupbossGroupnewNioEventLoopGroup(1);privatestaticfinalEventLoopGroupworkerGroupnewNioEventLoopGroup();publicvoidstartServer(intport){try{ServerBootstrapsbsnewServerBootstrap()。group(bossGroup,workerGroup)。channel(NioServerSocketChannel。class)。localAddress(newInetSocketAddress(port))。childHandler(newChannelInitializerSocketChannel(){protectedvoidinitChannel(SocketChannelch)throwsException{ch。pipeline()。addLast(framer,newDelimiterBasedFrameDecoder(8192,Delimiters。lineDelimiter()));ch。pipeline()。addLast(decoder,newStringDecoder());ch。pipeline()。addLast(encoder,newStringEncoder());ch。pipeline()。addLast(newHelloWorldServerHandler());}})。option(ChannelOption。SOBACKLOG,128)。childOption(ChannelOption。SOKEEPALIVE,true);绑定端口,开始接收进来的连接sbs。bind(port)。addListener(future{log。info(String。format(服务器启动成功,并监听端口:s,port));});}catch(Exceptione){log。error(启动netty服务器端出现异常,e);}}服务器端启动,并绑定19080端口PostConstructpublicvoidinit(){ForkJoinPool。commonPool()。submit(()startServer(19080));}PreDestroypublicvoiddestroy(){bossGroup。shutdownGracefully();workerGroup。shutdownGracefully();}}服务器端HelloWorldServerHandler如下packagecom。ckjava。test。importio。netty。channel。ChannelHandlerCimportio。netty。channel。ChannelInboundHandlerAimportlombok。extern。slf4j。Slf4j;Slf4jpublicclassHelloWorldServerHandlerextendsChannelInboundHandlerAdapter{服务器端读取到客户端发送过来的数据,然后通过Channel回写数据OverridepublicvoidchannelRead(ChannelHandlerContextctx,Objectmsg){log。info(String。format(服务器端读取到从客户端:s发送过来的数据:s,ctx。channel()。remoteAddress(),msg。toString()));ctx。channel()。writeAndFlush(String。format(serverwrite:s,msg));}捕获到异常的处理OverridepublicvoidexceptionCaught(ChannelHandlerContextctx,Throwablecause){cause。printStackTrace();ctx。close();}}client客户端通过PostConstruct注解的方法进行启动,具体如下packagecom。ckjava。test。importio。netty。bootstrap。Bimportio。netty。channel。Cimportio。netty。channel。ChannelFimportio。netty。channel。ChannelIimportio。netty。channel。ChannelOimportio。netty。channel。ChannelPimportio。netty。channel。EventLoopGimportio。netty。channel。nio。NioEventLoopGimportio。netty。channel。socket。SocketCimportio。netty。channel。socket。nio。NioSocketCimportio。netty。handler。codec。string。StringDimportio。netty。handler。codec。string。StringEimportio。netty。util。concurrent。Fimportio。netty。util。concurrent。GenericFutureLimportlombok。extern。slf4j。Slf4j;importorg。springframework。stereotype。Cimportjavax。annotation。PostCimportjavax。annotation。PreDimportjava。util。concurrent。ForkJoinPSlf4jComponentpublicclassHelloWorldClient{staticfinalintSIZEInteger。parseInt(System。getProperty(size,256));privatefinalEventLoopGroupgroupnewNioEventLoopGroup();privateChannelFuturemChannelFprivatefinalThreadLocalChannelmChannelnewThreadLocal();publicvoidstartClient(Stringhost,intport){Configuretheclient。try{BootstrapbnewBootstrap();b。group(group)。channel(NioSocketChannel。class)。option(ChannelOption。TCPNODELAY,true)。handler(newChannelInitializerSocketChannel(){OverridepublicvoidinitChannel(SocketChannelch)throwsException{ChannelPipelinepch。pipeline();p。addLast(decoder,newStringDecoder());p。addLast(encoder,newStringEncoder());p。addLast(newHelloWorldClientHandler());}});mChannelFutureb。connect(host,port)。addListener(future{log。info(String。format(客户端启动成功,并监听端口:s,port));});}catch(Exceptione){log。error(启动netty客户端出现异常,e);}}客户端通过Channel对象向服务器端发送数据paramdata文本数据publicvoidsend(Stringdata){try{if(mChannel。get()null){mChannel。set(mChannelFuture。channel());}mChannel。get()。writeAndFlush(data);}catch(Exceptione){log。error(this。getClass()。getName()。concat(。sendhaserror),e);}}客户端启动,并连上服务器端PostConstructpublicvoidinit(){ForkJoinPool。commonPool()。submit(()startClient(127。0。0。1,19080));}PreDestroypublicvoiddestroy(){group。shutdownGracefully();}}客户端HelloWorldClientHandler实现如下packagecom。ckjava。test。importio。netty。channel。ChannelHandlerCimportio。netty。channel。ChannelInboundHandlerAimportlombok。extern。slf4j。Slf4j;Slf4jpublicclassHelloWorldClientHandlerextendsChannelInboundHandlerAdapter{客户端激活监听OverridepublicvoidchannelActive(ChannelHandlerContextctx){log。info(客户端激活!);}客户端读取从服务器端发送过来的消息OverridepublicvoidchannelRead(ChannelHandlerContextctx,Objectmsg){log。info(String。format(客户端读取从服务器端发送过来的数据:s,msg));}捕获异常OverridepublicvoidexceptionCaught(ChannelHandlerContextctx,Throwablecause){cause。printStackTrace();ctx。close();}}webapi数据发送入口这里只是通过packagecom。ckjava。test。importcom。ckjava。test。client。HelloWorldCimportio。swagger。annotations。Aimportorg。springframework。web。bind。annotation。GetMimportorg。springframework。web。bind。annotation。RequestMimportorg。springframework。web。bind。annotation。RequestPimportorg。springframework。web。bind。annotation。RestCimportjavax。annotation。Rimportjavax。servlet。http。HttpServletRimportjavax。servlet。http。HttpServletRauthorckjavadate202241823:50ApiRequestMapping(charsetutf8)RestControllerpublicclassHelloNettyCtrl{ResourceprivateHelloWorldClientmHelloWorldCGetMapping(nettyClient)publicvoidnettyClient(RequestParamStringdata)throwsException{mHelloWorldClient。send(data);}}测试执行如下请求curlXGEThttp:localhost:8080nettyClient?dataE4BDA0E5A5BD20ckjavaHaccept:charsetutf8输出如下22:36:00。178〔nioEventLoopGroup41〕INFOc。c。t。server。HelloWorldServerHandler服务器端读取到从客户端:127。0。0。1:9196发送过来的数据:你好ckjava22:36:00。178〔nioEventLoopGroup21〕INFOc。c。t。client。HelloWorldClientHandler客户端读取从服务器端发送过来的数据:serverwrite:你好ckjava
投诉 评论 转载

我把一个人从我的微信里删除了,他怎么又进来了,确实删掉了,这微信现在已成为人们社交的主要社交软件,目前微信的活跃量已经超越10亿用户。几乎每个成年人至少有一个微信,微信在通讯录好友管理里面和以前的社交软件QQ不同,并没有QQ权限那么多,……巨一科技董秘回复公司将积极开拓包括小米华为等在内的客户巨一科技(688162)02月07日在投资者关系平台上答复了投资者关心的问题。投资者:董秘,您好,小米汽车正式落户北京亦庄目标两期累计年产30万辆车,除了造车新势力与传统……快递不上门为何成了潜规则?在快递不上门的问题争论多年后,又一明确的强制罚款措施即将出台。近日,国家邮政局就《快递市场管理办法(修订草案)》公开征求意见,其中提到,经营快递业务的企业未经用户同意,不……七夕来了,送女友什么呢?看看ikbc阴阳师联名茨球乐队键盘前言一年一度的七夕节又双叒叕来了,各位男生女生有没有收到女朋友或男朋友各种暗示、明示、威逼、利诱?选礼物一直是比较头疼的事情,像我这种直男都是直接问你想要什么,一般都会被……预算再低,也不要买64G手机手持3年64G小米8,更新于2021年9月26日凌晨1点,对于我这种手机钉子户来说,手机更换频率是极低的,再便宜的手机也能坚持个35年。但是现在我已经不知道多少次想把自己的手机……realme作为OPPO子品牌,却在短时间内迅速崛起众所周知,OPPO同Vivo,都出自步步高旗下,而realme则是OPPO的子品牌。品牌简介realme在2018年8月28日创立,是一家专注于智能手机和AIoT产品的科……联想小新Air14Plus2021酷睿版发布i51155G7从联想小新官方获悉,联想正式推出了小新Air14Plus2021酷睿版,这款产品搭载i51155G7处理器,配备MX450显卡以及16GB的内存和512GBSSD。据了解……行业卷王卢伟冰,红米K50超大杯的打法连雷军看了都怕今晚红米K50系列就要发布了,一直以来红米都是性价比的代名词。得益于去年红米K40拿下的超高销量和超高口碑,让很多朋友都非常期待今年的红米K50系列。尤其是超大杯的K50Pro……至晟微电子发布新一代5G微基站氮化镓PA集微网消息,近年来,随着5G通信、物联网等技术的发展和应用逐步落地,射频微波作为其中的关键技术之一也得到了快速发展,相关应用呈爆发式增长的态势。在广阔的市场需求和国内政策大力支……在springboot项目中集成Netty进行消息发送和接收概述本文通过一个简单的demo来介绍Netty在springboot项目中的使用,其中包括了服务器端和客户端的启动代码,客户端向服务器端发送文本消息。maven依赖dep……福特发布重组计划电动汽车业务独立运营,未来将独立上市?21世纪经济报道记者杜巧梅报道在2021年成为仅次于特斯拉的美国第二大电动汽车生产商之后,福特汽车正在加速其电动化转型步伐。北京时间3月2日晚,福特汽车对外宣布成立独立运……小到无敌?JEETAir2耳机体验兼顾了舒适和音质无线蓝牙耳机已经完全成为了主流趋势,毕竟现在大部分手机都取消了3。5毫米耳机接口,而且我也实在不想每次摸出耳机的时候都在那里理线,所以无线耳机真的已经成为了我的选择。我用过不下……
沃尔玛官网提前上架Onn品牌AndroidTV电视棒和4K机华为Mate40E国产率仅56,其中一个5G零件,难倒大批中大型科技公司的气候承诺是否过于雄心勃勃?此刻看手机的你,用的是什么品牌的手机?市值将达5000亿美元!西媒起底光刻机巨头阿斯麦中兴通讯2022年第一季度净利22。17亿同比增长1。6汇兑新能源汽车时代,合资品牌路在何方未来篇转型加速,未来可期人工智能卫星遥感耕种湖南高科技保粮食稳产央视发声,华为内部潜伏西方间谍,华为设备到底安不安全?院士欧阳明高中国固态电池追赶日本至少要五年哈勃望远镜发现迄今最遥远单颗恒星shell脚本大全
长袖t恤裙怎么搭配什么裤子你穿对了吗数学广场掷数点块教学设计空调保温棉怎样安装安装空调保温棉步骤介绍详解盛泽时尚周文化赋能时尚诗意雅韵诠释中国美学新教练上任,正所谓一朝天子一朝臣,谁会是巴黎周期女排队长呢?风暖式浴霸哪种好风暖式浴霸特点详解体育课上的小插曲的五年级作文如何知道是不是你心中的那个人昨夜,又见一帘幽梦秒钟造句用秒钟造句大全一路走来,愿所有相遇,都恰逢其时我不愿做机器人

友情链接:中准网聚热点快百科快传网快生活快软网快好知文好找江西南阳嘉兴昆明铜陵滨州广东西昌常德梅州兰州阳江运城金华广西萍乡大理重庆诸暨泉州安庆南充武汉辽宁