首页 > 其他分享 >Netty WebSocket客户端

Netty WebSocket客户端

时间:2023-01-24 10:31:32浏览次数:57  
标签:netty WebSocket Netty WebSocketClientHandler handler io import channel 客户端


参考:​​https://www.jianshu.com/p/f8f99f20d7f4​


WebSocketClient.java


package com.flash.client;

import com.flash.handler.WebSocketClientHandler;
import com.flash.log.Log;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.net.URI;

public class WebSocketClient {

public boolean ConnWebSocketServerAsync(String svrUrl){
Thread thd = new Thread(){
@Override
public void run() {
ConnWebSocketServer(svrUrl);
}
};
thd.start();
return true;
}

public boolean ConnWebSocketServer(String svrUrl){
EventLoopGroup client = new NioEventLoopGroup();
try{
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(client);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.channel(NioSocketChannel.class);
bootstrap.handler(new WebSocketClientInit());

URI wsURI = new URI(svrUrl); // new URI("ws://localhost:8899/ws");
ChannelFuture cf = bootstrap.connect(wsURI.getHost(), wsURI.getPort()).sync();
cf.addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
String log = "";
log = String.format("连接websocket服务器: %s isSuccess=%s", svrUrl, channelFuture.isSuccess());
System.out.println(log);
if(channelFuture.isSuccess()){
//进行握手
Channel channel = channelFuture.channel();
HttpHeaders httpHeaders = new DefaultHttpHeaders();
WebSocketClientHandler handler = (WebSocketClientHandler)channel.pipeline().get("WebSocketClientHandler");
WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(wsURI,
WebSocketVersion.V13, (String)null, true, httpHeaders);
handler.setHandshaker(handshaker);
handshaker.handshake(channel);

// 阻塞等待是否握手成功?
// handler.handshakeFuture().sync();
handler.handshakeFuture();

}
}
});

cf.channel().closeFuture().sync();
return true;
}
catch (Exception ex){
Log.ErrorLog(ex);
}
finally {
client.shutdownGracefully();
}
return false;
} // ConnWebSocketServer end


}


WebSocketClientInit.java


package com.flash.client;

import com.flash.handler.WebSocketClientHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;

public class WebSocketClientInit extends ChannelInitializer<SocketChannel> {

@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("HttpClientCodec", new HttpClientCodec());
pipeline.addLast("HttpObjectAggregator", new HttpObjectAggregator(1024*10));
pipeline.addLast("WebSocketClientHandler", new WebSocketClientHandler());
}
}


WebSocketClientHandler.java


package com.flash.handler;

import com.flash.log.Log;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;

public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {
private WebSocketClientHandshaker handshaker = null;
private ChannelPromise handshakeFuture = null;

public void handlerAdded(ChannelHandlerContext ctx) {
this.handshakeFuture = ctx.newPromise();
}

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
Log.DebugLog("WebSocketClientHandler::channelRead0: ");

// 握手协议返回,设置结束握手
if (!this.handshaker.isHandshakeComplete()){
FullHttpResponse response = (FullHttpResponse)msg;
this.handshaker.finishHandshake(ctx.channel(), response);
this.handshakeFuture.setSuccess();
Log.DebugLog("WebSocketClientHandler::channelRead0 HandshakeComplete...");
return;
}

if (msg instanceof TextWebSocketFrame) {
TextWebSocketFrame textFrame = (TextWebSocketFrame)msg;
Log.DebugLog("WebSocketClientHandler::channelRead0 textFrame: " + textFrame.text());
}

if (msg instanceof CloseWebSocketFrame){
Log.DebugLog("WebSocketClientHandler::channelRead0 CloseWebSocketFrame");
}
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// System.out.println("WebSocketClientHandler::channelInactive 服务端连接成功");
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("WebSocketClientHandler::exceptionCaught");
cause.printStackTrace();
ctx.channel().close();
}

public void setHandshaker(WebSocketClientHandshaker handshaker) {
this.handshaker = handshaker;
}

public ChannelFuture handshakeFuture() {
return this.handshakeFuture;
}

public ChannelPromise getHandshakeFuture() {
return handshakeFuture;
}

public void setHandshakeFuture(ChannelPromise handshakeFuture) {
this.handshakeFuture = handshakeFuture;
}

}

 

 

 

 

 

标签:netty,WebSocket,Netty,WebSocketClientHandler,handler,io,import,channel,客户端
From: https://blog.51cto.com/softo/6022189

相关文章

  • 如何用Python实现http客户端和服务器
    功能:客户端可以向服务器发送get,post等请求,而服务器端可以接收这些请求,并返回给客户端消息。客户端:#coding=utf-8importhttp.clientfromurllibimportrequest,pars......
  • 用AutoHotkey解决B站客户端缓存视频m4s合并成mp4提示解析失败
    一直用you-get下载B站视频,这两天发现视频的质量很低,于是又折腾了下在线播放有1080P,而you-get-i{url}返回的最高清晰度就是480P听朋友安利用哔哩下载姬(DownKyi),试了也......
  • Netty
    Netty1.什么是Netty?Netty是由JBOSS提供的一个Java开源框架。异步的、基于事件驱动的网络应用程序框架,用以快速开发高性能、高可靠性的网络IO程序。Netty......
  • [ros]4.客户端和服务端
    目录客户端实现创建功能包代码实现编译服务端实现创建功能包代码实现编译客户端实现和发布者不同的是客户端只有向服务端发出请求后服务端才会产生应答,这种机制应用在一......
  • 基于WebSocket的实时消息传递设计
    目录概述整体架构设计流程设计程序设计WebSocketServer概述新增pom新增配置类创建websocket端点WebSocketClient概述安装WebSocketSharp初始化client创建连接接口设计新增......
  • 请不要再说NIO和多路复用IO是同一个东西了(内含BIO、NIO、多路复用、Netty、AIO案例测
    文章目录​​一、写在最前面​​​​1、误区​​​​2、IO模型分类​​​​3、概念再梳理(重点)​​​​二、BIO(BlockingIO)​​​​1、客户端​​​​2、服务端​​​​3、效......
  • 浅谈Netty中ServerBootstrap服务端源码(含bind全流程)
    文章目录​​一、梳理Java中NIO代码​​​​二、Netty服务端代码​​​​1、newNioEventLoopGroup()​​​​2、group​​​​3、channel​​​​4、NioServerSocketChanne......
  • 客户端实现GridView全选全不选
    Code:1.<scripttype="text/javascript">2.function3.{4.varchecks=document.getElementById('<%=GridView1.ClientID%>');5.if(sender.chec......
  • 基于Netty的HashedWheelTimer实现延迟任务
    packagecom.cmcc.open.ota.config;importio.netty.util.HashedWheelTimer;importio.netty.util.Timeout;importio.netty.util.TimerTask;importlombok.extern.s......
  • iSCSI的客户端messages频繁报错问题解决
    问题现象:在自己的工作站中安装的RAC测试环境,使用了iSCSI模拟共享存储,环境运行OK,但是在messages信息中频繁报错如下:[root@db01rac2~]#tail-20f/var/log/messagesJan......