WebSocket - Netty服务端构建

本文详细介绍了如何使用Netty构建WebSocket服务端,包括入门案例、Netty内置处理类的使用以及SpringBoot的整合方案。通过实例展示了WebSocket全双工通信的优势,并提供了WebSocket客户端的JAVA实现。
摘要由CSDN通过智能技术生成

WebSocket - Netty服务端/客户端构建

文章目录
在线websocket测试-online tool-postjson (coolaf.com)
WebSocket协议深入探究 - 云+社区 - 腾讯云 (tencent.com)
/

一、概要

初步总结几句话

  1. 是单个TCP连接上的全双工通信协议
  2. 服务端与客户端之间仅需一次握手,即可创建持久性连接进行双向数据传输

WebSocket和Socket的区别

  • Socket:客户端主动请求,服务器被动应答,单向数据传输;
  • WebSocket:全双工模式,仅需一次握手;

实际上,WebSocket使用的场景在于实时要求高的场景。

二、基于Netty构建WebSocket服务端

2.1 入门案例

NettyServer基本配置

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
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;

/**
 * @author 李家民
 */
public class NettyServer {
   
    public void ServerStart() throws InterruptedException {
   
        // 连接请求处理
        EventLoopGroup bossGroup = new NioEventLoopGroup(3);
        // IO请求处理
        EventLoopGroup workerGroup = new NioEventLoopGroup(5);
        // 基本配置
        ServerBootstrap serverBootstrap =
                new ServerBootstrap().group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .option(ChannelOption.SO_BACKLOG, 128)
                        .childOption(ChannelOption.SO_KEEPALIVE, true);
        // 处理器管道配置
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
   
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
   
                System.out.println("此时客户端进来了:" + "客户 SocketChannel hashcode=" + ch.hashCode());
                ChannelPipeline pipeline =
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
netty-websocket-spring-boot-starter是一个基于Netty实现的WebSocket框架,可以方便地在Spring Boot应用中集成WebSocket功能。使用该框架可以快速构建实时通信、消息推送等功能。 下面是一个使用netty-websocket-spring-boot-starter的简单案例: 1. 在pom.xml中添加依赖: ```xml <dependency> <groupId>com.github.wujiuye</groupId> <artifactId>netty-websocket-spring-boot-starter</artifactId> <version>1.0.0.RELEASE</version> </dependency> ``` 2. 编写WebSocket处理器 ```java @ServerEndpoint("/websocket/{userId}") @Component public class WebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); private Session session; private String userId; @OnOpen public void onOpen(Session session, @PathParam("userId") String userId) { this.session = session; this.userId = userId; logger.info("WebSocket连接建立,userId: {}", userId); } @OnMessage public void onMessage(String message) { logger.info("收到来自客户端的消息:{}", message); sendMessage("服务端已收到消息:" + message); } @OnClose public void onClose() { logger.info("WebSocket连接关闭,userId: {}", userId); } @OnError public void onError(Throwable t) { logger.error("WebSocket连接异常,userId: {}", userId, t); } public void sendMessage(String message) { try { this.session.getBasicRemote().sendText(message); } catch (IOException e) { logger.error("发送WebSocket消息失败,userId: {}", userId, e); } } } ``` 3. 配置WebSocket 在配置类中添加@EnableWebSocket注解,启用WebSocket功能,同时,也可以配置WebSocket的一些参数,例如端口号、路径等。 ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private WebSocketHandler webSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler, "/websocket/{userId}") .setAllowedOrigins("*"); } } ``` 4. 测试WebSocket 使用浏览器或WebSocket客户端连接WebSocket服务端,例如:ws://localhost:8080/websocket/123,其中123为userId。 以上就是一个简单的netty-websocket-spring-boot-starter使用案例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值