住房和城乡建设部官方网站已前程无忧招聘网
news/
2025/10/6 22:22:56/
文章来源:
住房和城乡建设部官方网站已,前程无忧招聘网,淄博的大型网站建设,岳阳网站平台设计需求#xff1a;项目中需要使用netty#xff0c;本地测试的时候使用的是ws#xff0c;然后要部署到服务器上#xff0c;使用https连接#xff0c;https下就不能用ws了#xff0c;必须升级到wss
1.阿里云申请免费证书
2.保存证书到本地目录
3.修改代码
SslUtil 工具类…需求项目中需要使用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升级为wssSslContext 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
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/929767.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!