前言
因为服务端只有一个,客户端可以有多个,且可能是前端的websocket客户端,后端的websocket客户端,因此目前我们的架构是java客户端整合好数据,然后要发送到浏览器的客户端,因此这里的做法是先将消息发送到websocket的服务端,然后统一由服务端解析发送数据的报文,然后转发给浏览器的websocket客户端,从而实现后端的websocket客户端发送消息给前端的websocket客户端。
1、websocket client的Bean实例的创建
package com.dscomm.spark.config;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.dscomm.spark.netty.handler.WebSocketClientHandler;
import com.dscomm.spark.netty.listener.LoginListener;
import com.dscomm.spark.netty.listener.ReconnectionListener;
import ds.afp.websocket.bean.CLMessage;
import ds.afp.websocket.bean.UserObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
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.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.net.ssl.SSLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.TimeUnit;
@PropertySource({"classpath:websocket.properties"})
@EnableApolloConfig("websocket")
@Configuration
public class MyNettyWebsocketClient {
private static Log logger = LogFactory.getLog(DsNettyWebsocketClient.class);
@Value("${websocket.type}")
private String type;
@Value("${websocket.id}")
private String id;
@Value("${websocket.system}")
private String system;
@Value("${websocket.serverIp}")
private String URL;
private static String host;
private s

本文介绍如何将基于Netty实现的WebSocket客户端集成到Spring中,包括WebSocket客户端Bean实例创建、Netty Handler配置、断开连接后的重连机制、连接成功后的登录验证以及在Service中调用发送消息的方法。此实现还支持心跳报文和可封装为服务供其他后端使用。

2587

被折叠的 条评论
为什么被折叠?



