• 依赖于Tomcat的webSocket地址后面是可以随便跟参数的,但是发现netty WebSocket却不能加参数,代码如下:
  • WebSocketServer.java
 package com.rw.article.chat.websocket;import com.rw.article.chat.action.ApiController;
import com.rw.article.chat.websocket.handler.BinaryWebSocketFrameHandler;
import com.rw.article.chat.websocket.handler.TextWebSocketHandler;
import com.rw.article.common.constant.Constants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** @author Zhou Zhong Qing* @Title: ${file_name}* @Package ${package_name}* @Description: WebSocket* @date 2019/4/16 17:26*/
public class WebSocketServer {private Logger log = LoggerFactory.getLogger(this.getClass()); // 日志对象public void main(String[] args) throws InterruptedException {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workGroup = new NioEventLoopGroup();try {ServerBootstrap bootstrap = new ServerBootstrap();bootstrap.group(bossGroup, workGroup).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true).handler(new LoggingHandler(LogLevel.TRACE)).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE))// HttpRequestDecoder和HttpResponseEncoder的一个组合,针对http协议进行编解码.addLast(new HttpServerCodec())// 分块向客户端写数据,防止发送大文件时导致内存溢出, channel.write(new ChunkedFile(new File("bigFile.mkv"))).addLast(new ChunkedWriteHandler())// 将HttpMessage和HttpContents聚合到一个完成的 FullHttpRequest或FullHttpResponse中,具体是FullHttpRequest对象还是FullHttpResponse对象取决于是请求还是响应// 需要放到HttpServerCodec这个处理器后面.addLast(new HttpObjectAggregator(10240))// webSocket 数据压缩扩展,当添加这个的时候WebSocketServerProtocolHandler的第三个参数需要设置成true.addLast(new WebSocketServerCompressionHandler())// 服务器端向外暴露的 web socket 端点,当客户端传递比较大的对象时,maxFrameSize参数的值需要调大.addLast(new WebSocketServerProtocolHandler(Constants.DEFAULT_WEB_SOCKET_LINK, null, true, 10485760))// 自定义处理器 - 处理 web socket 文本消息.addLast(new TextWebSocketHandler())// 自定义处理器 - 处理 web socket 二进制消息.addLast(new BinaryWebSocketFrameHandler());}});ChannelFuture channelFuture = bootstrap.bind(8092).sync();log.info("webSocket server listen on port : [{}]", 8092);channelFuture.channel().closeFuture().sync();} finally {bossGroup.shutdownGracefully();workGroup.shutdownGracefully();}}
}
  • 网上搜索了下说是要重写uri,然后我自己debug了程序发现调用了WebSocketServerProtocolHandler#channelRead方法,我可以从msg中拿到uri并重写,但是发现不行,后面我把handler的执行顺序改了下就可以了。
  • WebSocketServer.java的更改
   // 自定义处理器 - 处理 web socket 文本消息.addLast(new TextWebSocketHandler())// 自定义处理器 - 处理 web socket 二进制消息.addLast(new BinaryWebSocketFrameHandler())// 服务器端向外暴露的 web socket 端点,当客户端传递比较大的对象时,maxFrameSize参数的值需要调大.addLast(new WebSocketServerProtocolHandler(Constants.DEFAULT_WEB_SOCKET_LINK, null, true, 10485760));
  • 然后我在TextWebSocketHandler重写uri
    TextWebSocketHandler.java
  package com.rw.article.chat.websocket.handler;import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.rw.article.chat.entity.vo.Message;
import com.rw.article.chat.queue.DelayOrderQueueManager;
import com.rw.article.chat.queue.DelayOrderWorker;
import com.rw.article.chat.websocket.OnlineContainer;
import com.rw.article.chat.websocket.protocol.IMsgCode;
import com.rw.article.chat.websocket.protocol.ProcessorContainer;
import com.rw.article.common.configuration.GenericConfiguration;
import com.rw.article.common.constant.Constants;
import com.rw.article.common.spring.BeansUtils;
import com.rw.article.common.type.MessageSendType;
import com.rw.article.common.type.MessageType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;import java.net.InetSocketAddress;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;/*** @author Zhou Zhong Qing* @Title: ${file_name}* @Package ${package_name}* @Description: 文本消息处理* @date 2019/4/16 17:29*/
public class TextWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {private Logger log = LoggerFactory.getLogger(this.getClass()); // 日志对象private OnlineContainer onlineContainer;private BeansUtils beansUtils;public TextWebSocketHandler() {onlineContainer = BeansUtils.getBean(OnlineContainer.class);}/*经过测试,在 ws 的 uri 后面不能传递参数,不然在 netty 实现 websocket 协议握手的时候会出现断开连接的情况。针对这种情况在 websocketHandler 之前做了一层 地址过滤,然后重写request 的 uri,并传入下一个管道中,基本上解决了这个问题。* */@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {if (null != msg && msg instanceof FullHttpRequest) {FullHttpRequest request = (FullHttpRequest) msg;// log.info("调用 channelRead request.uri() [ {} ]", request.uri());String uri = request.uri();// log.info("Origin [ {} ] [ {} ]", request.headers().get("Origin"), request.headers().get("Host"));String origin = request.headers().get("Origin");if (null == origin) {log.info("origin 为空 ");ctx.close();} else {if (null != uri && uri.contains(Constants.DEFAULT_WEB_SOCKET_LINK) && uri.contains("?")) {String[] uriArray = uri.split("\\?");if (null != uriArray && uriArray.length > 1) {String[] paramsArray = uriArray[1].split("=");if (null != paramsArray && paramsArray.length > 1) {onlineContainer.putAll(paramsArray[1], ctx);          }}request.setUri(Constants.DEFAULT_WEB_SOCKET_LINK);}} else {log.info("不允许 [ {} ] 连接 强制断开", origin);ctx.close();}}super.channelRead(ctx, msg);}@Overrideprotected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {log.info("接收到客户端的消息:[{}]", msg.text());// 如果是向客户端发送文本消息,则需要发送 TextWebSocketFrame 消息InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();String ip = inetSocketAddress.getHostName();String txtMsg = "[" + ip + "][" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")) + "] ==> " + msg.text();//TODO 这是发给自己ctx.channel().writeAndFlush(new TextWebSocketFrame(txtMsg));}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {//移除maponlineContainer.removeAll(ctx.channel().id().asLongText());ctx.close();log.error("服务器发生了异常: [ {} ]", cause);}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {// 添加//log.info(" 客户端加入 [ {} ]", ctx.channel().id().asLongText());super.channelActive(ctx);}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {// 移除//log.info(" 离线 [ {} ] ", ctx.channel().id().asLongText());super.channelInactive(ctx);//移除mapString key = onlineContainer.removeAll(ctx.channel().id().asLongText());ctx.close();}}
  • 全部代码可参考netty webSocket

netty WebSocket后面加参数相关推荐

  1. netty websocket客户端_Websocket操作字节序 之 服务端

    Websocket在JavaScript中操作字节序 之 客户端 在上一篇文章中,把页面的websocket编码写好了,那么服务端又该如何实现呢?由于该文是在上上篇demo中修改的,所以不全的代码还请 ...

  2. 基于netty+websocket实现门户游客实时统计功能

    基于netty+websocket实现门户游客实时统计功能 基本需求 商城门户页面需要实时展示游客访问的数量,商城后台页面需要实时游客访问量.登录用户数量,以及下订单用户数量. 技术选型 1.首先实时 ...

  3. Netty实战,Springboot + netty +websocket 实现推送消息

    开发者(KaiFaX) 面向全栈工程师的开发者专注于前端.Java/Python/Go/PHP的技术社区 来源 | blog.csdn.net/weixin_44912855 学过 Netty 的都知 ...

  4. Netty 快速开始(netty websocket客户端使用流程)

    文章目录 一.网络IO的基本知识与概念 1. 同步.异步.阻塞.非阻塞概念 2. IO模型 3. NIO和IO有什么区别? 4. Java NIO 工作流程 二.netty 1. 什么是netty? ...

  5. SpringBoot2+Netty+WebSocket(netty实现websocket)

    ##### 一.SpringBoot2+Netty+WebSocket(netty实现websocket,支持URL参数) 原文链接: https://zhengkai.blog.csdn.net/a ...

  6. netty整合websocket支持自签证书出现netty websocket ssl Received fatal alert: certificate_unknown

    自签证书 win+r cmd 生成自己jks文件,指向自己要生成jks的文件位置下,我直接生成到项目resources下 #换成自己的本地ip keytool -genkey -alias serve ...

  7. Spring boot 项目(二十三)——用 Netty+Websocket实现聊天室

    Netty的介绍 Netty 是基于 Java NIO 的异步事件驱动的网络应用框架,使用 Netty 可以快速开发网络应用,Netty 提供了高层次的抽象来简化 TCP 和 UDP 服务器的编程,但 ...

  8. netty服务器定时发送消息,netty+websocket+quartz实现消息定时推送

    netty+websocket+quartz实现消息定时推送&&IM聊天室 在讲功能实现之前,我们先来捋一下底层的原理,后面附上工程结构及代码 1.NIO NIO主要包含三大核心部分: ...

  9. 在xml文件的Preference标签中,用extra给intent标签加参数

    2019独角兽企业重金招聘Python工程师标准>>> 在xml文件的Preference标签中,用<extra>给<Intent>标签加参数,以及<i ...

最新文章

  1. vs创建html页面提示未找到,VS2015 打开html 提示 未能完成操作 解决办法
  2. php 不允许外部访问,[日常] 解决mysql不允许外部访问
  3. 微型计算机硬件性能取决于什么,微型计算机硬件系统的性能主要取决于
  4. 1864. [ZJOI2006]三色二叉树【树形DP】
  5. java中类的命名规则_java类方法属性的命名规范介绍
  6. 他35k月薪,如何扛住redis面试!
  7. 计算机导航医学应用,【2016年】计算机导航在全膝关节置换中的应用技术及进展【临床医学论文】.doc...
  8. 位运算求两个数的平均值
  9. 水晶报表2008部署
  10. 卷积神经网络 第三周作业 Keras+-+Tutorial+-+Happy+House+v1
  11. 产品经理入门知识梳理(含思维导图
  12. Can总线dbc文件解析代码
  13. tbody css 高度,html – CSS:无法为%滚动设置tbody height
  14. 设计师出差必备的5款移动端设计软件
  15. 【Devc++】战斗1.0.2
  16. unity3d学习笔记(一)方向键移动物体
  17. 绿色IT,从环保到经济效益
  18. 袋式过滤器 - - 过滤与分离的基本原理,结构和布局的控制袋式过滤器
  19. 社会工程学三本_1.9万人报考,扩招近千人!被戏称为“大三本”的985——东南大学,低调有实力!...
  20. Python_Task03:异常处理

热门文章

  1. AB测试需要知道的知识
  2. python loads_load 和 loads的区别
  3. java int取高位8bit_byte解析,取高位与低位
  4. 工银二维码支付享受满减,超低汇率千分二
  5. EPEL到底是什么,为何经常要安装epel-release软件包
  6. 麦角硫因/超级抗氧化
  7. QQ服务器系统有哪些小功能,腾讯企点服务是什么?有哪些系统功能
  8. Kepserver Modbus 高低字节问题
  9. Java 8 reduce()方法快速使用入门
  10. MagicBattery产品免责声明