ws升级为wss

本文介绍了如何在Netty项目中,从使用ws协议升级到https的wss协议,包括从PKCS1格式证书转换为PKCS8格式,以及在代码中添加SslUtil和WebSocketServerProtocolHandler的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:项目中需要使用netty,本地测试的时候使用的是ws,然后要部署到服务器上,使用https连接,https下就不能用ws了,必须升级到wss

1.阿里云申请免费证书

2.保存证书到本地目录
在这里插入图片描述

3.修改代码

SslUtil 工具类

import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

import java.io.File;

/**
 * netty 证书
 */
public class SslUtil {

    private static final File pemFile = new File("C:\\Users\\Lenovo\\Desktop\\zhengshu\\server.pem");
    private static final File keyFile = new File("C:\\Users\\Lenovo\\Desktop\\zhengshu\\server.key");

    public static SslContext createSSLContext() throws Exception {
        SslContext sslCtx = SslContextBuilder.forServer(pemFile, keyFile).clientAuth(ClientAuth.NONE).build();
        return sslCtx;
    }
 }

自定义handler中增加代码

@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();
    //ws升级为wss
    SslContext sslCtx = SslUtil.createSSLContext();
    pipeline.addLast(sslCtx.newHandler(socketChannel.alloc()));
    //30秒客户端没有向服务器发送心跳则关闭连接
    pipeline.addLast(new IdleStateHandler(15, 0, 0));
    // 因为使用http协议,所以需要使用http的编码器,解码器
    pipeline.addLast(new HttpServerCodec());
    // 以块方式写,添加 chunkedWriter 处理器
    pipeline.addLast(new ChunkedWriteHandler());
    /**
     * 说明:
     *  1. http数据在传输过程中是分段的,HttpObjectAggregator可以把多个段聚合起来;
     *  2. 这就是为什么当浏览器发送大量数据时,就会发出多次 http请求的原因
     */
    pipeline.addLast(new HttpObjectAggregator(8192));
    /**
     * 说明:
     *  1. 对于 WebSocket,它的数据是以帧frame 的形式传递的;
     *  2. 可以看到 WebSocketFrame 下面有6个子类
     *  3. 浏览器发送请求时: ws://localhost:7000/hello 表示请求的uri
     *  4. WebSocketServerProtocolHandler 核心功能是把 http协议升级为 ws 协议,保持长连接;
     *      是通过一个状态码 101 来切换的
     */
    pipeline.addLast(new WebSocketServerProtocolHandler("/websocket"));
    // 自定义handler ,处理业务逻辑
    pipeline.addLast(new NettyWebSocketServerHandler());
}
});

增加这两行代码

SslContext sslCtx = SslUtil.createSSLContext();
pipeline.addLast(sslCtx.newHandler(socketChannel.alloc()));

4.测试

结果报错:
在这里插入图片描述
原因:查阅资料netty仅仅支持pkcs8,当前为pem/key的格式的,也就是PKCS1的

证书格式区别:

  • PKCS1的文件头格式 -----BEGIN RSA PRIVATE KEY-----
  • PKCS8的文件头格式 -----BEGIN PRIVATE KEY-----

解决:将证书(server.key) 通过OpenSSl 生成pkcs8的版本

1.下载OpenSSL https://www.oomake.com/download/openssl 下载 OpenSSL 3.0.0 Windows 64位 Light 版.exe 版本

2.将安装了路径加到环境变量中

3.在证书目录打开cmd,执行下面命令

openssl pkcs8 -topk8 -inform PEM -in server.key -outform pem -nocrypt -out server8.key

在这里插入图片描述

修改SslUtil工具类中路径

private static final File keyFile = new File("C:\\Users\\Lenovo\\Desktop\\zhengshu\\server8.key");

4.打开postman再次测试

我的websocket端口配置的是9000

访问:ws://127.0.0.1:9000/websocket

会报错 io.netty.handler.codec.DecoderException: io.netty.handler.ssl.NotSslRecordException: not an SSL/TLS record

访问:wss://127.0.0.1:9000/websocket 连接成功,至此ws成功升级为wss

在这里插入图片描述

### 如何从 WS 升级WSS 并配置 SSL 证书 为了将 WebSocket (WS) 服务升级至 WebSocket Secure (WSS),并添加 SSL/TLS 证书以实现安全连接,需遵循一系列特定的配置步骤。这不仅涉及服务器端的安全设置调整,还可能涉及到客户端应用代码的小幅修改。 #### Spring Boot 配置 SSL 证书 对于基于 Spring Boot 的应用程序,在项目中引入依赖后,仅需在 `application.properties` 或者 `application.yml` 文件内指定必要的 SSL 参数即可完成 HTTPS 和 WSS 支持[^2]: ```yaml server: port: 8443 ssl: key-store-type: PKCS12 key-store: classpath:keystore.p12 key-password: "password" ``` 上述配置使得 Spring Boot 应用程序能够监听 8443 端口上的 HTTPS 请求,并自动处理来自同一主机名下的 WSS 连接请求。 #### Nginx 反向代理与 SSL 终止 当使用 Nginx 作为反向代理时,可以在此处终止 SSL 握手过程并将未加密的数据发给内部的应用服务器。Nginx 的配置文件应包含如下所示的部分内容来启用此功能[^4]: ```nginx server { listen 443 ssl; server_name example.com; ssl_certificate /etc/nginx/cert/example.com.crt; ssl_certificate_key /etc/nginx/cert/example.com.key; location /websocket/ { proxy_pass http://backend_websocket_service; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } ``` 这段配置指示 Nginx 监听 443 端口上带有 SSL 加密流量的同时,针对路径 `/websocket/` 下发起的 WebSocket 请求执行协议升级操作 (`Upgrade`) ,从而允许建立 WSS 连接。 #### Java Netty 实现自定义 SSL 上下文 如果是在较低级别的网络框架比如 Netty 中工作,则可以通过编程方式创建 SSL 上下文对象,并将其应用于 ChannelPipeline 来保护通信链路[^3]: ```java import io.netty.handler.ssl.SslContext; // ... SslContext sslCtx = SslUtil.createSSLContext(); pipeline.addLast(sslCtx.newHandler(socketChannel.alloc())); ``` 以上代码片段展示了如何利用 Netty 提供的功能构建一个简单的 SSL Handler,并把它加入到管道末端以便于后续的消息传递过程中实施数据加密解密逻辑。 通过这些方法之一或组合起来运用,就可以成功地把现有的 WS 接口换成更安全可靠的 WSS 版本了。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值