Java io.netty.util.ReferenceCountUtil 代码实例
原文:https://www.helplib.com/Java_API_Classes/article_64580
实例 1
private static void testPerformOpeningHandshake0(boolean subProtocol) {
EmbeddedChannel ch = new EmbeddedChannel(
new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());
FullHttpRequest req = ReferenceCountUtil.releaseLater(
new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat"));
req.headers().set(Names.HOST, "server.example.com");
req.headers().set(Names.UPGRADE, WEBSOCKET.toLowerCase());
req.headers().set(Names.CONNECTION, "Upgrade");
req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com");
req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
req.headers().set(Names.SEC_WEBSOCKET_VERSION, "13");
if (subProtocol) {
new WebSocketServerHandshaker13(
"ws://example.com/chat", "chat", false, Integer.MAX_VALUE).handshake(ch, req);
} else {
new WebSocketServerHandshaker13(
"ws://example.com/chat", null, false, Integer.MAX_VALUE).handshake(ch, req);
}
ByteBuf resBuf = (ByteBuf) ch.readOutbound();
EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
ch2.writeInbound(resBuf);
HttpResponse res = (HttpResponse) ch2.readInbound();
Assert.assertEquals(
"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(Names.SEC_WEBSOCKET_ACCEPT));
if (subProtocol) {
Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
} else {
Assert.assertNull(res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
}
ReferenceCountUtil.release(res);
}
实例 2
@Test
public void testHttpUpgradeRequest() throws Exception {
EmbeddedChannel ch = createChannel(new MockOutboundHandler());
ChannelHandlerContext handshakerCtx = ch.pipeline().context(WebSocketServerProtocolHandshakeHandler.class);
writeUpgradeRequest(ch);
assertEquals(SWITCHING_PROTOCOLS, ReferenceCountUtil.releaseLater(responses.remove()).getStatus());
assertNotNull(WebSocketServerProtocolHandler.getHandshaker(handshakerCtx));
}
实例 3
@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Class<?> messageClass = msg.getClass();
if (!handshaker.isHandshakeComplete()) {
ctx.pipeline().remove(HttpObjectAggregator.class);
handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
httpChannel = new NettyHttpChannel(tcpStream, new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/")) {
@Override
protected void doSubscribeHeaders(Subscriber<? super Void> s) {
Publishers.<Void>empty().subscribe(s);
}
};
NettyHttpWSClientHandler.super.channelActive(ctx);
super.channelRead(ctx, msg);
return;
}
if (TextWebSocketFrame.class.isAssignableFrom(messageClass)) {
try {
//don't inflate the String bytes now
channelSubscriber.onNext(new StringBuffer(((TextWebSocketFrame) msg).content().nioBuffer()));
} finally {
ReferenceCountUtil.release(msg);
}
} else if (CloseWebSocketFrame.class.isAssignableFrom(messageClass)) {
ctx.close();
} else {
doRead(ctx, ((WebSocketFrame)msg).content());
}
}
实例 4
@SuppressWarnings("unchecked")
protected final void doRead(ChannelHandlerContext ctx, Object msg) {
try {
if (null == channelSubscriber || msg == Unpooled.EMPTY_BUFFER) {
ReferenceCountUtil.release(msg);
return;
}
NettyBuffer buffer = NettyBuffer.create(msg);
try {
channelSubscriber.onNext(buffer);
}
finally {
if (buffer.getByteBuf() != null) {
if (buffer.getByteBuf()
.refCnt() != 0) {
ReferenceCountUtil.release(buffer.getByteBuf());
}
}
}
}
catch (Throwable err) {
Exceptions.throwIfFatal(err);
if (channelSubscriber != null) {
channelSubscriber.onError(err);
}
else {
throw err;
}
}
}
实例 5
/**
* Test try to reproduce issue #1335
*/
@Test
public void testBindMultiple() throws Exception {
DefaultChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
NioEventLoopGroup group = new NioEventLoopGroup();
try {
for (int i = 0; i < 100; i++) {
Bootstrap udpBootstrap = new Bootstrap();
udpBootstrap.group(group).channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// Discard
ReferenceCountUtil.release(msg);
}
});
DatagramChannel datagramChannel = (DatagramChannel) udpBootstrap
.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
channelGroup.add(datagramChannel);
}
Assert.assertEquals(100, channelGroup.size());
} finally {
channelGroup.close().sync();
group.shutdownGracefully().sync();
}
}
实例 6
@BeforeClass
public static void init() {
// Configure a test server
group = new LocalEventLoopGroup();
ServerBootstrap sb = new ServerBootstrap();
sb.group(group)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// Discard
ReferenceCountUtil.release(msg);
}
});
}
});
localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
}
实例 7
@BeforeClass
public static void init() {
// Configure a test server
group = new LocalEventLoopGroup();
ServerBootstrap sb = new ServerBootstrap();
sb.group(group)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// Discard
ReferenceCountUtil.release(msg);
}
});
}
});
localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
}
实例 8
@Override
public ChannelGroupFuture write(Object message, ChannelMatcher matcher) {
if (message == null) {
throw new NullPointerException("message");
}
if (matcher == null) {
throw new NullPointerException("matcher");
}
Map<Channel, ChannelFuture> futures = new LinkedHashMap<Channel, ChannelFuture>(size());
for (Channel c: nonServerChannels) {
if (matcher.matches(c)) {
futures.put(c, c.write(safeDuplicate(message)));
}
}
ReferenceCountUtil.release(message);
return new DefaultChannelGroupFuture(this, futures, executor);
}
实例 9
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (isRemote(ctx)) {
ByteBuf payload = (ByteBuf) msg;
byte[] data = getPayloadFromByteBuf(payload);
writeBuffer(data);
return;
}
ReferenceCountUtil.retain(msg);
// propagate the data to rest of handlers in pipeline
ctx.fireChannelRead(msg);
}
实例 10
@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
// The first message must be authentication response
if (this.authenticationUrl != null && (this.cookies == null || this.cookies.isEmpty())) {
HttpResponse response = (HttpResponse) msg;
CharSequence cookieData = response.headers().get(new AsciiString("set-cookie"));
if (cookieData != null) {
this.cookies = ServerCookieDecoder.decode(cookieData.toString());
if (this.cookies == null || this.cookies.isEmpty()) {
throw new WebSocketAuthenticationFailureException("Could not authenticate");
}
if (log.isDebugEnabled()) {
for (Cookie cookie : this.cookies) {
log.debug("Server says must set cookie with name {} and value {}", cookie.name(), cookie.value());
}
}
} else {
throw new ITException("Could not authenticate");
}
if (log.isDebugEnabled()) {
log.debug("Authentication succeeded for user {}", this.user);
}
handShaker.handshake(ctx.channel());
return;
}
// The second one must be the response for web socket handshake
if (!handShaker.isHandshakeComplete()) {
handShaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
if (log.isDebugEnabled()) {
log.debug("Web socket client connected for user {}", this.user);
}
handshakeFuture.setSuccess();
return;
}
// Take the byte buff and send it up to Stomp decoder
if (msg instanceof WebSocketFrame) {
if (log.isDebugEnabled()) {
if (msg instanceof TextWebSocketFrame) {
log.debug("Received text frame {}", ((TextWebSocketFrame) msg).text());
}
}
ReferenceCountUtil.retain(msg);
ctx.fireChannelRead(((WebSocketFrame) msg).content());
}
}
实例 11
@Override
protected void encode(ChannelHandlerContext ctx, DefaultHttpMessage defaultHttpMessage, List out) throws Exception {
if (defaultHttpMessage.headers().contains(HttpHeaders.CONTENT_LENGTH, "", true)) {
defaultHttpMessage.headers().remove(HttpHeaders.CONTENT_LENGTH);
}
ReferenceCountUtil.retain(defaultHttpMessage);
out.add(defaultHttpMessage);
}
实例 12
private static Object safeDuplicate(Object message) {
if (message instanceof ByteBuf) {
return ((ByteBuf) message).duplicate().retain();
} else if (message instanceof ByteBufHolder) {
return ((ByteBufHolder) message).duplicate().retain();
} else {
return ReferenceCountUtil.retain(message);
}
}
实例 13
@Override
public void onNext(T t) {
// Retain so that post-buffer, the ByteBuf does not get released.
// Release will be done after reading from the subject.
ReferenceCountUtil.retain(t);
state.bufferedObserver.onNext(t);
// Schedule timeout once and when not subscribed yet.
if (state.casTimeoutScheduled() && state.state == State.STATES.UNSUBSCRIBED.ordinal()) {
timeoutScheduler.subscribe(new Action1<Long>() { // Schedule timeout after the first content arrives.
@Override
public void call(Long aLong) {
disposeIfNotSubscribed();
}
});
}
}
实例 14
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
Channel channel = ctx.channel();
if (msg instanceof HttpRequest) {
HttpRequest request = (HttpRequest) msg;
if (handleRequest(request, channel, ctx)) {
if (httpMethodInfoBuilder.getHttpResourceModel()
.isStreamingReqSupported() &&
channel.pipeline().get("aggregator") != null) {
channel.pipeline().remove("aggregator");
} else if (!httpMethodInfoBuilder.getHttpResourceModel()
.isStreamingReqSupported() &&
channel.pipeline().get("aggregator") == null) {
channel.pipeline().addAfter("router", "aggregator",
new HttpObjectAggregator(Integer.MAX_VALUE));
}
}
ReferenceCountUtil.retain(msg);
ctx.fireChannelRead(msg);
} else if (msg instanceof HttpContent) {
ReferenceCountUtil.retain(msg);
ctx.fireChannelRead(msg);
}
}
实例 15
@Override
public void onData(final ByteBuf input) {
// We need to retain until the serializer gets around to processing it.
ReferenceCountUtil.retain(input);
serializer.execute(new Runnable() {
@Override
public void run() {
if (isTraceBytes()) {
TRACE_BYTES.info("Received: {}", ByteBufUtil.hexDump(input));
}
ByteBuffer source = input.nioBuffer();
do {
ByteBuffer buffer = protonTransport.getInputBuffer();
int limit = Math.min(buffer.remaining(), source.remaining());
ByteBuffer duplicate = source.duplicate();
duplicate.limit(source.position() + limit);
buffer.put(duplicate);
protonTransport.processInput();
source.position(source.position() + limit);
} while (source.hasRemaining());
ReferenceCountUtil.release(input);
// Process the state changes from the latest data and then answer back
// any pending updates to the Broker.
processUpdates();
pumpToProtonTransport();
}
});
}
Java io.netty.util.ReferenceCountUtil 代码实例的更多相关文章
- 记一次netty版本冲突,报java.lang.NoSuchMethodError: io.netty.util.internal.ObjectUtil.checkPositive的问题
elasticsearch 5.6中使用TransportClient初始化抛异常 在引入elasticsearch5.6的transportclient包中,会引入netty进行通信. <!- ...
- Netty 5 io.netty.util.IllegalReferenceCountException 异常
异常信息 io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1 原因 handler 继承了 SimpleChan ...
- 编译Netty源码遇到的一些问题-缺少io.netty.util.collection包
缺少包和java类 下载好Netty的源码后,导入到IDE,运行自带的example时编译不通过. 如下图,是因为io.netty.util.collection的包没有 点进去看,确实没有这个包 发 ...
- netty-websocket-spring-boot-starter关闭报错 io/netty/channel/AbstractChannel$AbstractUnsafe io/netty/util/concurrent/GlobalEventExecutor
报错 java.lang.NoClassDefFoundError: io/netty/channel/AbstractChannel$AbstractUnsafe$ at io.netty.chan ...
- Java生成MD5加密字符串代码实例
这篇文章主要介绍了Java生成MD5加密字符串代码实例,本文对MD5的作用作了一些介绍,然后给出了Java下生成MD5加密字符串的代码示例,需要的朋友可以参考下 (1)一般使用的数据库中都会保存用 ...
- netty/example/src/main/java/io/netty/example/http/snoop/
netty/example/src/main/java/io/netty/example/http/snoop at 4.1 · netty/netty https://github.com/nett ...
- Java中的匿名对象代码实例
/* 匿名对象:就是没有名字的对象. 匿名对象的应用场景: A:调用场景,仅仅只调用一次的时候. 注意:调用多次的时候,不合适. 那么,这种匿名调用有什么好处吗? 有,匿名对象调用完毕就是垃圾.可以被 ...
- 【Java】浅谈Java IO
注意 本文的代码,为了学习方便,简化代码复杂度,未考虑拆包.粘包等情况的处理.所以仅供学习使用,不能用于实际环境. 阻塞IO,BIO Java1.1发布的IO是BIO.阻塞地连接之后,通过流进行同步阻 ...
- 漫谈Java IO之普通IO流与BIO服务器
今天来复习一下基础IO,也就是最普通的IO. 网络IO的基本知识与概念 普通IO以及BIO服务器 NIO的使用与服务器Hello world Netty的使用与服务器Hello world 输入流与输 ...
随机推荐
- Python实现 -- 冒泡排序、选择排序、插入排序
冒泡排序 冒泡排序(Bubble Sort),是一种计算机科学领域的较简单的排序算法. 冒泡排序的原理: 比较两个相邻的元素,如果第一个比第二个大,就交换他们 对每一对相邻的元素做同样的工作,从开始第 ...
- 07 Go 1.7 Release Notes
Go 1.7 Release Notes Introduction to Go 1.7 Changes to the language Ports Known Issues Tools Assembl ...
- Android 6.0 API
Android 6.0 (M) 为用户和应用开发者提供了新功能.本文旨在介绍其中最值得关注的 API. 着手开发 要着手开发 Android 6.0 应用,您必须先获得 Android SDK,然后使 ...
- 使用 Gradle 对应用进行个性化定制
啥也不说了,直接进入主题吧.本篇文章主要根据实际开发中遇到的需求,讲解使用 Gradle 对应用的不同版本进行个性化定制. 场景介绍 一般的应用基本上都有正式服和测试服,这个就不需要多说了.但是有些应 ...
- Coursera台大机器学习技法课程笔记12-Neural Network
由perceptron线性组成的一个神经网络: 通过赋予g不同的权值,来实现不同的切分功能: 但有的切分只通过一次特征转换是不够的,需要多次转换,如下: Neural Network Hypothes ...
- oracle 中 dblink 的简单使用
oracle 中 dblink 的简单使用 dblink的作用 当用户要跨本地数据库,访问另外一个数据库表中的数据时,本地数据库中必须创建了远程数据库的dblink,通过dblink本地数据库可以像访 ...
- 洛谷P3964 [TJOI2013]松鼠聚会 [二分答案,前缀和,切比雪夫距离]
题目传送门 松鼠聚会 题目描述 草原上住着一群小松鼠,每个小松鼠都有一个家.时间长了,大家觉得应该聚一聚.但是草原非常大,松鼠们都很头疼应该在谁家聚会才最合理. 每个小松鼠的家可以用一个点x,y表示, ...
- P1679 神奇的四次方数
P1679 神奇的四次方数用一些什么东西组成一个什么东西,要求什么东西最优,这时候要考虑背包,不过要分析清楚是什么类型的背包.这题显然是个完全背包. #include<iostream> ...
- js数组去重与性能分析(时间复杂度很重要)
随着js的深入和实际项目对性能的要求,算法的简单实现已经不能满足需要,在不同的应用场景下,时间复杂度很重要. 首先是创建数组与性能处理函数: // 保证时间差的明显程度,创建不同量级的数组,size为 ...
- 【python学习-3】python数据类型
1.数字 在python 2.x中,数字类型有4种,int.long.float 和 complex(复数):而python 3 中,只有 int.float 和 complex 3种,python ...