​ 前面三章介绍了Netty的一些基本用法,这一章介绍怎么使用Netty来实现一个简单的长连接demo。

关于长连接的背景知识,可以参考《如何使用Socket实现长连接》

​ 一个简单的长连接demo分为以下几个步骤:

长连接流程
  1. 创建连接(Channel)
  2. 发心跳包
  3. 发消息,并通知其他用户
  4. 一段时间没收到心跳包或者用户主动关闭之后关闭连接

​ 看似简单的步骤,里面有两个技术难点:

  1. 如何保存已创建的Channel

    这里我们是将Channel放在一个Map中,以Channel.hashCode()作为key

    其实这样做有一个劣势,就是不适合水平扩展,每个机器都有一个连接数的上线,如果需要实现多用户实时在线,对机器的数量要求会很高,在这里我们不多做讨论,不同的业务场景,设计方案也是不同的,可以在长连接方案和客户端轮询方案中进行选择。

  2. 如何自动关闭没有心跳的连接

    Netty有一个比较好的Feature,就是ScheduledFuture,他可以通过ChannelHandlerContext.executor().schedule()创建,支持延时提交,也支持取消任务,这就给我们心跳包的自动关闭提供了一个很好的实现方案。

开始动手

​ 首先,我们需要用一个JavaBean来封装通信的协议内容,在这里我们只需要三个数据就行了:

  1. type : byte,表示消息的类型,有心跳类型和内容类型
  2. length : int,表示消息的长度
  3. content : String,表示消息的内容(心跳包在这里没有内容)

​ 然后,因为我们需要将Channel和ScheduledFuture缓存在Map里面,所以需要将两个对象组合成一个JavaBean。

​ 接着,需要完成输入输出流的解析和转换,我们需要重写Decoder和Encoder,具体可以参考Netty笔记3-Decoder和Encoder

​ 最后,就是需要完成ChannelHandler了,代码如下:

package com.dz.netty.live;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.ScheduledFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit; /**
* Created by RoyDeng on 17/7/20.
*/
public class LiveHandler extends SimpleChannelInboundHandler<LiveMessage> { // 1 private static Map<Integer, LiveChannelCache> channelCache = new HashMap<>();
private Logger logger = LoggerFactory.getLogger(LiveHandler.class); @Override
protected void channelRead0(ChannelHandlerContext ctx, LiveMessage msg) throws Exception {
Channel channel = ctx.channel();
final int hashCode = channel.hashCode();
System.out.println("channel hashCode:" + hashCode + " msg:" + msg + " cache:" + channelCache.size()); if (!channelCache.containsKey(hashCode)) {
System.out.println("channelCache.containsKey(hashCode), put key:" + hashCode);
channel.closeFuture().addListener(future -> {
System.out.println("channel close, remove key:" + hashCode);
channelCache.remove(hashCode);
});
ScheduledFuture scheduledFuture = ctx.executor().schedule(
() -> {
System.out.println("schedule runs, close channel:" + hashCode);
channel.close();
}, 10, TimeUnit.SECONDS);
channelCache.put(hashCode, new LiveChannelCache(channel, scheduledFuture));
} switch (msg.getType()) {
case LiveMessage.TYPE_HEART: {
LiveChannelCache cache = channelCache.get(hashCode);
ScheduledFuture scheduledFuture = ctx.executor().schedule(
() -> channel.close(), 5, TimeUnit.SECONDS);
cache.getScheduledFuture().cancel(true);
cache.setScheduledFuture(scheduledFuture);
ctx.channel().writeAndFlush(msg);
break;
}
case LiveMessage.TYPE_MESSAGE: {
channelCache.entrySet().stream().forEach(entry -> {
Channel otherChannel = entry.getValue().getChannel();
otherChannel.writeAndFlush(msg);
});
break;
}
}
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
logger.debug("channelReadComplete");
super.channelReadComplete(ctx);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.debug("exceptionCaught");
if(null != cause) cause.printStackTrace();
if(null != ctx) ctx.close();
}
}

​ 写完服务端之后,我们需要有客户端连接来测试这个项目,教程参考如何使用Socket在客户端实现长连接,代码如下:

package com.dz.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Scanner; /**
* Created by RoyDeng on 18/2/3.
*/
public class LongConnTest { private Logger logger = LoggerFactory.getLogger(LongConnTest.class); String host = "localhost";
int port = 8080; public void testLongConn() throws Exception {
logger.debug("start");
final Socket socket = new Socket();
socket.connect(new InetSocketAddress(host, port));
Scanner scanner = new Scanner(System.in);
new Thread(() -> {
while (true) {
try {
byte[] input = new byte[64];
int readByte = socket.getInputStream().read(input);
logger.debug("readByte " + readByte);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
int code;
while (true) {
code = scanner.nextInt();
logger.debug("input code:" + code);
if (code == 0) {
break;
} else if (code == 1) {
ByteBuffer byteBuffer = ByteBuffer.allocate(5);
byteBuffer.put((byte) 1);
byteBuffer.putInt(0);
socket.getOutputStream().write(byteBuffer.array());
logger.debug("write heart finish!");
} else if (code == 2) {
byte[] content = ("hello, I'm" + hashCode()).getBytes();
ByteBuffer byteBuffer = ByteBuffer.allocate(content.length + 5);
byteBuffer.put((byte) 2);
byteBuffer.putInt(content.length);
byteBuffer.put(content);
socket.getOutputStream().write(byteBuffer.array());
logger.debug("write content finish!");
}
}
socket.close();
} // 因为Junit不支持用户输入,所以用main的方式来执行用例
public static void main(String[] args) throws Exception {
new LongConnTest().testLongConn();
}
}

运行main方法之后,输入1表示发心跳包,输入2表示发content,5秒内不输入1则服务端会自动断开连接。

Netty入门4之----如何实现长连接的更多相关文章

  1. Netty入门教程——认识Netty

    什么是Netty? Netty 是一个利用 Java 的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的 API 的客户端/服务器框架. Netty 是一个广泛使用的 Java 网络编程框架(N ...

  2. Netty学习——通过websocket编程实现基于长连接的双攻的通信

    Netty学习(一)基于长连接的双攻的通信,通过websocket编程实现 效果图,客户端和服务器端建立起长连接,客户端发送请求,服务器端响应 但是目前缺少心跳,如果两个建立起来的连接,一个断网之后, ...

  3. Netty入门——客户端与服务端通信

    Netty简介Netty是一个基于JAVA NIO 类库的异步通信框架,它的架构特点是:异步非阻塞.基于事件驱动.高性能.高可靠性和高可定制性.换句话说,Netty是一个NIO框架,使用它可以简单快速 ...

  4. Netty实现服务端客户端长连接通讯及心跳检测

    通过netty实现服务端与客户端的长连接通讯,及心跳检测.        基本思路:netty服务端通过一个Map保存所有连接上来的客户端SocketChannel,客户端的Id作为Map的key.每 ...

  5. 通过netty实现服务端与客户端的长连接通讯,及心跳检测。

    基本思路:netty服务端通过一个Map保存所有连接上来的客户端SocketChannel,客户端的Id作为Map的key.每次服务器端如果要向某个客户端发送消息,只需根据ClientId取出对应的S ...

  6. Netty(一) SpringBoot 整合长连接心跳机制

    前言 Netty 是一个高性能的 NIO 网络框架,本文基于 SpringBoot 以常见的心跳机制来认识 Netty. 最终能达到的效果: 客户端每隔 N 秒检测是否需要发送心跳. 服务端也每隔 N ...

  7. 网络编程懒人入门(八):手把手教你写基于TCP的Socket长连接

    本文原作者:“水晶虾饺”,原文由“玉刚说”写作平台提供写作赞助,原文版权归“玉刚说”微信公众号所有,即时通讯网收录时有改动. 1.引言 好多小白初次接触即时通讯(比如:IM或者消息推送应用)时,总是不 ...

  8. 基于netty实现的长连接,心跳机制及重连机制

    技术:maven3.0.5 + netty4.1.33 + jdk1.8   概述 Netty是由JBOSS提供的一个java开源框架.Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速 ...

  9. 京东的Netty实践,京麦TCP网关长连接容器架构

    背景 早期京麦搭建 HTTP 和 TCP 长连接功能主要用于消息通知的推送,并未应用于 API 网关.随着逐步对 NIO 的深入学习和对 Netty 框架的了解,以及对系统通信稳定能力越来越高的要求, ...

随机推荐

  1. docker jenkins使用(二)

    jenkins的安装很简单,但是jenkins的初次使用却很头疼.对于小白来说有点不太明白 背景: 开发更新app需要很多步骤,生成jar包.上传服务器.更新启动程序,如果有很多服务器,那么需要做好多 ...

  2. Vue生命周期钩子详解【个人解读】

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. es第四篇:Query DSL

    Query and filter context Match All Query 最简单的search请求,匹配所有文档,文档的_score值都是1,示例: get twitter/_search{  ...

  4. (转)MySQL性能调优my.cnf详解

    MySQL性能调优my.cnf详解 https://blog.linuxeye.cn/379.html http://blog.csdn.net/orichisonic/article/details ...

  5. JDBC(3)-使用PreparedStatement接口实现增、删、改操作

    1.PreparedStatement接口引入 PreparedStatement是Statement的子接口,属于预处理操作,与直接使用Statement不同的是,PreparedStatement ...

  6. js 字符串转dom 和dom 转字符串

    js 字符串转dom 和dom 转字符串 博客分类: JavaScript   前言: 在javascript里面动态创建标准dom对象一般使用: var obj = document.createE ...

  7. Frequency-tuned Salient Region Detection MATLAB代码出错修改方法

    论文:Frequency-tuned Salient Region Detection.CVPR.2009 MATLAB代码运行出错如下: Error using makecform>parse ...

  8. 常用工具说明--GitHub团队项目合作流程

    注:其中 零.一.七 是由团队项目负责人来完成的.开发人员只要从 二 开始就行了. 零.前期准备: 首先把队友直接push的权限关掉,即设置成Read.这样可以防止队友误操作,未经审核就把代码push ...

  9. [转]浅谈 .NET Framework 与 .NET Core 的区别与联系

    本文转自:http://www.cnblogs.com/huchaoheng/p/6295688.html 2017到了,咱们学点啥啊,要想知道学点啥,先弄清.NET Framework 与 .NET ...

  10. 如何理解animation-fill-mode及其使用?<转>

    今天看了css3的动画,对animation的其他属性都比较容易理解,唯独这个animation-fill-mode让我操碎了心. 找了些下面的描述: 规定对象动画时间之外的状态. 有四个值可选,并且 ...