使用Netty实现websocket java client

本文档介绍了如何使用Netty代替Java自带的Nio来实现WebSocket Java客户端,旨在解决在OpenJDK环境下可能出现的CPU占用过高的问题。文中详细阐述了连接建立、发送登录报文、断线重连策略、连接管理和定时发送心跳等关键步骤。

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

由于使用Java自带的Nio编写websocket的java客户端时,使用的是java_websocket_client,然后在openjdk下出现cpu暴增问题,因此使用netty实现websocket的java客户端,并集成到Spring中


提示:以下是本篇文章正文内容,下面案例可供参考


一、实现websocet连接

package com.wsjkk.netty.websocket;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

/**
 * This is an example of a WebSocket client.
 * <p>
 * In order to run this example you need a compatible WebSocket server.
 * Therefore you can either start the WebSocket server from the examples
 * by running {@link io.netty.example.http.websocketx.server}
 * or connect to an existing WebSocket server such as
 * <a href="/https://www.websocket.org/echo.html"&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值