SpringBoot整合Netty处理WebSocket(支持url参数)

SpringBoot整合Netty处理WebSocket(支持url参数)

这篇文章是参考SpringBoot2+Netty+WebSocket(netty实现websocket,支持URL参数)这个博客文章进行编写完善的,有兴趣可以多多关注原博主。

后面经过自己的研究,看了Netty相关的WebSocket处理代码,重新写了一篇文章使用Netty处理WebSocket请求,可以更加优雅的处理WebSocket请求。


添加MAVEN依赖

<!-- Netty -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.45.Final</version>
</dependency>

WebSocketProperties配置类

为了能在SpringBoot项目中灵活配置相关的值,这里使用了配置类,并使用了默认值。

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "chat.websocket")
public class WebSocketProperties {

  private Integer port = 8081; // 监听端口
  private String path = "/ws"; // 请求路径
  private Integer boss = 2; // bossGroup线程数
  private Integer work = 2; // workGroup线程数

}

WebSocket连接通道池

用来管理已经连接的客户端通道,方便数据传输交互。

@Slf4j
@Component
public class NioWebSocketChannelPool {

  private final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

  /**
   * 新增一个客户端通道
   *
   * @param channel
   */
  public void addChannel(Channel channel) {
    channels.add(channel);
  }

  /**
   * 移除一个客户端连接通道
   *
   * @param channel
   */
  public void removeChannel(Channel channel) {
    channels.remove(channel);
  }

}

请求路径工具类

public class RequestUriUtils {

  /**
   * 将路径参数转换成Map对象,如果路径参数出现重复参数名,将以最后的参数值为准
   * @param uri 传入的携带参数的路径
   * @return
   */
  public static Map<String, String> getParams(String uri) {
    Map<String, String> params = new HashMap<>(10);

    int idx = uri.indexOf("?");
    if (idx != -1) {
      String[] paramsArr = uri.substring(idx + 1).split("&");

      for (String param : paramsArr) {
        idx = param.indexOf("=");
        params.put(param.substring(0, idx), param.substring(idx + 1));
      }
    }

    return params;
  }

  /**
   * 获取URI中参数以外部分路径
   * @param uri
   * @return
   */
  public static String getBasePath(String uri) {
    if (uri == null || uri.isEmpty())
      return null;

    int idx = uri.indexOf("?");
    if (idx == -1)
      return uri;

    return uri.substring(0, idx);
  }

}

WebSocket连接数据接收处理类

@Slf4j
@Sharable
@Component
public class NioWebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

  @Autowired
  private NioWebSocketChannelPool webSocketChannelPool;
  @Autowired
  private WebSocketProperties webSocketProperties;

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    log.debug("客户端连接:{}", ctx.channel().id());
    webSocketChannelPool.addChannel(ctx.channel());
    super.channelActive(ctx);
  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    log.debug("客户端断开连接:{}", ctx.channel().id());
    webSocketChannelPool.removeChannel(ctx.channel());
    super.channelInactive(ctx);
  }

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) {
    ctx.channel().flush();
  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
    // 根据请求数据类型进行分发处理
    if (frame instanceof PingWebSocketFrame) {
      pingWebSocketFrameHandler(ctx, (PingWebSocketFrame) frame);
    } else if (frame instanceof TextWebSocketFrame) {
      textWebSocketFrameHandler(ctx, (TextWebSocketFrame) frame);
    } else if (frame instanceof CloseWebSocketFrame) {
      closeWebSocketFrameHandler(ctx, (CloseWebSocketFrame) frame);
    }
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    log.info("客户端请求数据类型:{}", msg.getClass());
    if (msg instanceof FullHttpRequest) {
      fullHttpRequestHandler(ctx, (FullHttpRequest) msg);
    }
    super.channelRead(ctx, msg);
  }

  /**
   * 处理连接请求,客户端WebSocket发送握手包时会执行这一次请求
   * @param ctx
   * @param request
   */
  private void fullHttpRequestHandler(ChannelHandlerContext ctx, FullHttpRequest request) {
    String uri = request.uri();
    Map<String, String> params = RequestUriUtils.getParams(uri);
    log.debug("客户端请求参数:{}", params);
    // 判断请求路径是否跟配置中的一致
    if (webSocketProperties.getPath().equals(RequestUriUtils.getBasePath(uri)))
      // 因为有可能携带了参数,导致客户端一直无法返回握手包,因此在校验通过后,重置请求路径
      request.setUri(webSocketProperties.getPath());
    else
      ctx.close();
  }

  /**
   * 客户端发送断开请求处理
   * @param ctx
   * @param frame
   */
  private void closeWebSocketFrameHandler(ChannelHandlerContext ctx, CloseWebSocketFrame frame) {
    ctx.close();
  }

  /**
   * 创建连接之后,客户端发送的消息都会在这里处理
   * @param ctx
   * @param frame
   */
  private void textWebSocketFrameHandler(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
    // 客户端发送过来的内容不进行业务处理,原样返回
    ctx.channel().writeAndFlush(frame.retain());
  }

  /**
   * 处理客户端心跳包
   * @param ctx
   * @param frame
   */
  private void pingWebSocketFrameHandler(ChannelHandlerContext ctx, PingWebSocketFrame frame) {
    ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
  }
}

WebSocket通道连接初始化

@Component
public class NioWebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

  @Autowired
  private WebSocketProperties webSocketProperties;
  @Autowired
  private NioWebSocketHandler nioWebSocketHandler;

  @Override
  protected void initChannel(SocketChannel socketChannel) {
    socketChannel.pipeline()
        .addLast(new HttpServerCodec())
        .addLast(new ChunkedWriteHandler())
        .addLast(new HttpObjectAggregator(8192))
        .addLast(nioWebSocketHandler)
        .addLast(new WebSocketServerProtocolHandler(webSocketProperties.getPath(), null, true, 65536));
  }
}

Netty服务端

服务器的初始化和销毁都交给Spring容器。

@Slf4j
@Component
public class NioWebSocketServer implements InitializingBean, DisposableBean {

  @Autowired
  private WebSocketProperties webSocketProperties;
  @Autowired
  private NioWebSocketChannelInitializer webSocketChannelInitializer;

  private EventLoopGroup bossGroup;
  private EventLoopGroup workGroup;
  private ChannelFuture channelFuture;

  @Override
  public void afterPropertiesSet() throws Exception {
    try {
      bossGroup = new NioEventLoopGroup(webSocketProperties.getBoss());
      workGroup = new NioEventLoopGroup(webSocketProperties.getWork());

      ServerBootstrap serverBootstrap = new ServerBootstrap();
      serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024)
          .group(bossGroup, workGroup)
          .channel(NioServerSocketChannel.class)
          .localAddress(webSocketProperties.getPort())
          .childHandler(webSocketChannelInitializer);

      channelFuture = serverBootstrap.bind().sync();
    } finally {
      if (channelFuture != null && channelFuture.isSuccess()) {
        log.info("Netty server startup on port: {} (websocket) with context path '{}'", webSocketProperties.getPort(), webSocketProperties.getPath());
      } else {
        log.error("Netty server startup failed.");
        if (bossGroup != null)
          bossGroup.shutdownGracefully().sync();
        if (workGroup != null)
          workGroup.shutdownGracefully().sync();
      }
    }
  }

  @Override
  public void destroy() throws Exception {
    log.info("Shutting down Netty server...");
    if (bossGroup != null)
      bossGroup.shutdownGracefully().sync();
    if (workGroup != null)
      workGroup.shutdownGracefully().sync();
    if (channelFuture != null)
      channelFuture.channel().closeFuture().syncUninterruptibly();
    log.info("Netty server shutdown.");
  }
}

到此,代码编写完成了。

以下是一个简单的 Spring Boot 整合 NettyWebSocket 实现音视频通话的前后端代码示例: 前端代码(HTML + JavaScript): ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Video Chat</title> <style> #localVideo, #remoteVideo { width: 320px; height: 240px; } </style> </head> <body> <video id="localVideo" autoplay muted></video> <video id="remoteVideo" autoplay></video> <script> var localVideo = document.querySelector('#localVideo'); var remoteVideo = document.querySelector('#remoteVideo'); var peerConnection; navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then(function (stream) { localVideo.srcObject = stream; peerConnection = new RTCPeerConnection(); peerConnection.addStream(stream); peerConnection.onaddstream = function(event) { remoteVideo.srcObject = event.stream; }; peerConnection.onicecandidate = function(event) { if (event.candidate) { sendIceCandidate(event.candidate); } }; startCall(); }) .catch(function (err) { console.log('getUserMedia error:', err); }); function startCall() { // 发送一个开始通话的消息给服务器 var socket = new WebSocket('ws://localhost:8080/videochat'); socket.onopen = function () { socket.send(JSON.stringify({ type: 'start' })); }; socket.onmessage = function (event) { var message = JSON.parse(event.data); if (message.type === 'offer') { peerConnection.setRemoteDescription(new RTCSessionDescription(message.offer)) .then(function () { return peerConnection.createAnswer(); }) .then(function (answer) { return peerConnection.setLocalDescription(answer); }) .then(function () { socket.send(JSON.stringify({ type: 'answer', answer: peerConnection.localDescription })); }) .catch(function (err) { console.log(err); }); } else if (message.type === 'iceCandidate') { peerConnection.addIceCandidate(new RTCIceCandidate(message.iceCandidate)) .catch(function (err) { console.log(err); }); } }; } function sendIceCandidate(candidate) { // 发送一个 ICE candidate 到服务器 var socket = new WebSocket('ws://localhost:8080/videochat'); socket.onopen = function () { socket.send(JSON.stringify({ type: 'iceCandidate', iceCandidate: candidate })); }; } </script> </body> </html> ``` 后端代码(Java + Netty): ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(videoChatHandler(), "/videochat").setAllowedOrigins("*"); } @Bean public WebSocketHandler videoChatHandler() { return new VideoChatHandler(); } } public class VideoChatHandler extends TextWebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(VideoChatHandler.class); private Session session; private RTCPeerConnection peerConnection; @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { logger.info("WebSocket connection established"); this.session = session; } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { String json = (String) message.getPayload(); JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); String type = jsonObject.get("type").getAsString(); if ("start".equals(type)) { startCall(); } else if ("offer".equals(type)) { String sdp = jsonObject.get("offer").getAsString(); SessionDescription offer = new SessionDescription(Type.OFFER, sdp); peerConnection.setRemoteDescription(offer); createAnswer(); } else if ("answer".equals(type)) { String sdp = jsonObject.get("answer").getAsString(); SessionDescription answer = new SessionDescription(Type.ANSWER, sdp); peerConnection.setLocalDescription(answer); sendAnswer(); } else if ("iceCandidate".equals(type)) { JsonObject iceCandidateJson = jsonObject.get("iceCandidate").getAsJsonObject(); IceCandidate iceCandidate = new IceCandidate(iceCandidateJson.get("sdpMid").getAsString(), iceCandidateJson.get("sdpMLineIndex").getAsInt(), iceCandidateJson.get("candidate").getAsString()); peerConnection.addIceCandidate(iceCandidate); } } private void startCall() { peerConnection = new RTCPeerConnection(); peerConnection.addStream(getMediaStream()); peerConnection.setIceCandidateListener(new IceCandidateListener() { @Override public void onIceCandidate(IceCandidate iceCandidate) { JsonObject message = new JsonObject(); message.addProperty("type", "iceCandidate"); JsonObject iceCandidateJson = new JsonObject(); iceCandidateJson.addProperty("sdpMid", iceCandidate.getSdpMid()); iceCandidateJson.addProperty("sdpMLineIndex", iceCandidate.getSdpMLineIndex()); iceCandidateJson.addProperty("candidate", iceCandidate.getCandidate()); message.add("iceCandidate", iceCandidateJson); try { session.sendMessage(new TextMessage(message.toString())); } catch (IOException e) { logger.error("Error sending ICE candidate", e); } } }); createOffer(); } private void createOffer() { peerConnection.createOffer(new CreateSessionDescriptionObserver() { @Override public void onSuccess(SessionDescription sessionDescription) { peerConnection.setLocalDescription(sessionDescription); sendOffer(); } @Override public void onFailure(Throwable throwable) { logger.error("Error creating offer", throwable); } }, new MediaConstraints()); } private void sendOffer() { JsonObject message = new JsonObject(); message.addProperty("type", "offer"); message.addProperty("offer", peerConnection.getLocalDescription().description); try { session.sendMessage(new TextMessage(message.toString())); } catch (IOException e) { logger.error("Error sending offer", e); } } private void createAnswer() { peerConnection.createAnswer(new CreateSessionDescriptionObserver() { @Override public void onSuccess(SessionDescription sessionDescription) { peerConnection.setLocalDescription(sessionDescription); sendAnswer(); } @Override public void onFailure(Throwable throwable) { logger.error("Error creating answer", throwable); } }, new MediaConstraints()); } private void sendAnswer() { JsonObject message = new JsonObject(); message.addProperty("type", "answer"); message.addProperty("answer", peerConnection.getLocalDescription().description); try { session.sendMessage(new TextMessage(message.toString())); } catch (IOException e) { logger.error("Error sending answer", e); } } private MediaStream getMediaStream() { MediaStream mediaStream = new MediaStream(); MediaConstraints constraints = new MediaConstraints(); MediaStreamTrack videoTrack = getVideoTrack(); mediaStream.addTrack(videoTrack); MediaStreamTrack audioTrack = getAudioTrack(); mediaStream.addTrack(audioTrack); return mediaStream; } private MediaStreamTrack getVideoTrack() { VideoCaptureModule videoCaptureModule = new VideoCaptureModule(); VideoCapturer videoCapturer = new Camera2Enumerator(VideoChatHandler.this.getContext()).createCapturer("0", null); VideoSource videoSource = peerConnection.createVideoSource(videoCapturer, new MediaConstraints()); VideoTrack videoTrack = peerConnection.createVideoTrack("video", videoSource); videoCapturer.startCapture(320, 240, 30); return videoTrack; } private MediaStreamTrack getAudioTrack() { AudioSource audioSource = peerConnection.createAudioSource(new MediaConstraints()); AudioTrack audioTrack = peerConnection.createAudioTrack("audio", audioSource); return audioTrack; } } ``` 其中,`VideoChatHandler` 类是 Netty 的 `WebSocketHandler` 的实现,用于处理 WebSocket 消息。在 `afterConnectionEstablished` 方法中,保存了 WebSocketSession 的引用。在 `handleMessage` 方法中,处理各种消息类型,包括开始通话、发送 offer、发送 answer、发送 ICE candidate 等。在 `startCall` 方法中,创建了一个 `RTCPeerConnection` 对象,并且添加了本地的媒体流。在 `createOffer` 方法中,创建了一个 offer,并设置为本地的 SDP。在 `sendOffer` 方法中,将 offer 发送给客户端。在 `createAnswer` 方法中,创建了一个 answer,并设置为本地的 SDP。在 `sendAnswer` 方法中,将 answer 发送给客户端。在 `getMediaStream` 方法中,创建了一个媒体流,包括视频和音频轨道。在 `getVideoTrack` 方法中,创建了一个视频轨道,使用了 Android 的 Camera2 API。在 `getAudioTrack` 方法中,创建了一个音频轨道。最后,通过 `WebSocketHandlerRegistry` 注册了 `VideoChatHandler`。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值