当前位置: 首页 > news >正文

netty实现websocket通信

调用注意:

1、端口一定要是可以访问的。

2、依赖必须注意和其他版本冲突,比如redis的springboot starter包,会与5.0+版本冲突。

 <netty.version>4.1.74.Final</netty.version>            
<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>${netty.version}</version>
</dependency>

首先创建socket服务


@Component
@Slf4j
public class NettyWebSocketServer extends Thread {public static String MsgCode = "GBK";public Integer port=8099;@Overridepublic void run() {startServer();}private void startServer() {EventLoopGroup bossGroup = null;EventLoopGroup workGroup = null;ServerBootstrap serverBootstrap = null;ChannelFuture future = null;try {//初始化线程组bossGroup = new NioEventLoopGroup();workGroup = new NioEventLoopGroup();//初始化服务端配置serverBootstrap = new ServerBootstrap();//绑定线程组serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class).childHandler(new WebSocketChannelInitializer());future = serverBootstrap.bind(new InetSocketAddress(port)).sync();log.info(" *************Web Socket服务端启动成功 Port:{}*********** ", port);} catch (Exception e) {log.error("Web Socket服务端启动异常", e);} finally {if (future != null) {try {future.channel().closeFuture().sync();} catch (InterruptedException e) {log.error("channel关闭异常:", e);}}if (bossGroup != null) {//线程组资源回收bossGroup.shutdownGracefully();}if (workGroup != null) {//线程组资源回收workGroup.shutdownGracefully();}}}}

创建WebSocketChannelInitializer,配置请求目录、handle类,以及请求的最大内容

public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {protected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline();pipeline.addLast(new HttpServerCodec());pipeline.addLast(new ChunkedWriteHandler());pipeline.addLast(new HttpObjectAggregator(5000));pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));pipeline.addLast(new TextWebSocketFrameHandle());}
}

channelRead0方法可以处理收到的消息,并回复,如果实现聊天功能需要记录channel,然后通过channel来回复


@Slf4j
public class TextWebSocketFrameHandle extends SimpleChannelInboundHandler<TextWebSocketFrame> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {log.info("收到消息:" + msg.text());ctx.channel().writeAndFlush(new TextWebSocketFrame("收到客户端消息"));}@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception {log.info("handlerAdded:" +ctx.channel().id().asLongText());}@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) throws Exception {log.info("handlerAdded:" +ctx.channel().id().asLongText());}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {log.error("异常发生");ctx.close();}
}

web调用的地址为:ws://localhost:8099/ws

http://www.lryc.cn/news/130416.html

相关文章:

  • 两个list如何根据一个list中的属性去过滤掉另一个list中不包含这部分的属性,用流实现
  • Blender 混合现实3D模型制作指南【XR】
  • kubeasz在线安装K8S集群单master集群(kubeasz安装之二)
  • 『C语言』数据在内存中的存储规则
  • 基于ssm+vue的新能源汽车在线租赁管理系统源码和论文PPT
  • 深入解析IDS/IPS与SSL/TLS和网络安全
  • 在Visual Studio上,使用OpenCV实现人脸识别
  • 搭建openGauss 5.0 一主一从复制集群
  • Docker碎碎念
  • 【C++】extern
  • 2023全网Mysql 合集(25w字)附课程 从安装到高级,实战
  • 张俊林:由ChatGPT反思大语言模型(LLM)的技术精要
  • 单机编排docker compose
  • C++ 面向对象三大特性——多态
  • 相同数字的积木游戏
  • 安防监控视频云存储EasyCVR平台H.265转码功能更新:新增分辨率配置
  • 图数据库_Neo4j学习cypher语言_常用函数_关系函数_字符串函数_聚合函数_数据库备份_数据库恢复---Neo4j图数据库工作笔记0008
  • LeetCode150道面试经典题-- 加一(简单)
  • Centos7 配置Docker镜像加速器
  • 微信小程序中pdf的上传、下载及excel导出
  • Python_11 类的方法
  • CentOS系统环境搭建(一)——Centos7更新
  • Mariadb高可用MHA
  • SASS 学习笔记 II
  • 提高 Snowflake 工作效率的 6 大工具
  • 选项方式读取配置IOption、IOptionSnapshot、IOpstionMonitor的区别
  • linux基础面试题整理
  • IDEA开发项目时一直出现http404错误的解决方法
  • NLPR、SenseTime 和 NTU 加速自动视频纵向编辑
  • layui下拉框select 弹出层在最外层