发布时间:2025-06-24 18:24:46 作者:北方职教升学中心 阅读量:650
总结
发布时间:2025-06-24 18:24:46 作者:北方职教升学中心 阅读量:650
总结
Maven版本3.6.3,在Maven文件夹下创建了res文件夹,做为Java工程的Maven本地仓库地址,此文件通常都在500MB以上,随着本地项目数而递增。改造服务端代码
查看数据结果
打开【Project Structure】
成功创建项目,Sringboot版本 2.7.6,Java版本8。
修改SDK、
我们在Debug数据时,可以看到msg的data类型
TextWebSocketFrame(data: PooledUnsafeDirectByteBuf(ridx: 0, widx: 61, cap: 61))
importio.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;importorg.springframework.context.annotation.Configuration;importio.netty.channel.socket.nio.NioServerSocketChannel;importio.netty.handler.codec.http.HttpObjectAggregator;importio.netty.handler.codec.http.HttpServerCodec;importio.netty.handler.stream.ChunkedWriteHandler;importio.netty.handler.timeout.IdleStateHandler;importio.netty.channel.nio.NioEventLoopGroup;importio.netty.channel.socket.SocketChannel;importio.netty.bootstrap.ServerBootstrap;importjavax.annotation.PostConstruct;importlombok.extern.slf4j.Slf4j;importio.netty.channel.*;@Slf4j@ConfigurationpublicclassNettyWebsocketServer{//bossGroup 连接线程组,主要负责接受客户端连接EventLoopGroupbossGroup =newNioEventLoopGroup(1);privateEventLoopGroupworkerGroup =newNioEventLoopGroup();privateChannelFuturechannelFuture;@PostConstructpublicvoidstart()throwsInterruptedException{try{ServerBootstrapb =newServerBootstrap();b.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,128).childOption(ChannelOption.SO_KEEPALIVE,true).childHandler(newChannelInitializer<SocketChannel>(){@OverrideprotectedvoidinitChannel(SocketChannelsocketChannel)throwsException{ChannelPipelinepipeline =socketChannel.pipeline();// 因为使用 HTTP 协议,所以需要 HTTP编码器,解码器pipeline.addLast(newHttpServerCodec());// 以块方式,添加 chunkedWriter 处理器pipeline.addLast(newChunkedWriteHandler());/** * 1. http数据在传输中是分段的,HttpObjectAggregator 可以把多个段聚合起来 * 2. 这就是为什么当浏览器发送大量数据时,就会发出多次 http请求的原因 */pipeline.addLast(newHttpObjectAggregator(8192));// 保存用户ip// pipeline.addLast(new HttpHeadersHandler());pipeline.addLast(newWebSocketServerProtocolHandler("/chat"));pipeline.addLast(newIdleStateHandler(60,5,0));pipeline.addLast(newChatHandler());//添加自定义handler}});// Bind and start to accept incoming connections.channelFuture =b.bind(9091).sync();if(channelFuture.isSuccess()){log.info("netty启动成功");}// 对通道关闭进行监听channelFuture.channel().closeFuture().sync();}finally{if(channelFuture !=null&&channelFuture.isSuccess()){System.out.println("Netty server started on port 9091");}else{System.err.println("Netty server failed to start");}}}}
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.68.Final</version><!-- 请根据需要选择合适的版本 --></dependency></dependencies>
输入ws接口地址,成功连接上netty服务
创建一个自定义的 ChannelHandler 来处理客户端的请求:
importio.netty.channel.ChannelHandlerContext;importio.netty.channel.ChannelInboundHandlerAdapter;publicclassChatHandlerextendsChannelInboundHandlerAdapter{@OverridepublicvoidchannelRead(ChannelHandlerContextctx,Objectmsg)throwsException{// 处理收到的消息System.out.println("Received message: "+msg);ctx.writeAndFlush("Message received: "+msg);}@OverridepublicvoidexceptionCaught(ChannelHandlerContextctx,Throwablecause)throwsException{cause.printStackTrace();ctx.close();}}
在Idea里创建Springboot工程,Language选择Java,Type选择Maven,Project SDK 选择Java8。客户端发送数据
检查Maven配置,主要检查settings.xml和本地Maven仓库
上述操作都是打基础,搭架子和配置环境,下一步我们需要加载netty 的相关依赖包。启动服务
客户端收不到服务端回复的消息。启动服务
在settings.xml里配置上阿里云镜像
<mirrors><mirror><id>alimaven</id><mirrorOf>central</mirrorOf><name>aliyun maven</name><url>http://maven.aliyun.com/nexus/content/repositories/central/</url></mirror></mirrors>
在文章里,我们实现了Springboot 集成netty,并使用apiFox客户端发送了消息到netty服务,最终客户端收到服务端的应答。Debug调试数据
这里可以看到已经接收到数据了。