Netty笔记4-如何实现长连接

前面三章介绍了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了,代码如下:

 
  1. package com.dz.netty.live;

  2.  
  3. import io.netty.channel.Channel;

  4. import io.netty.channel.ChannelHandlerContext;

  5. import io.netty.channel.SimpleChannelInboundHandler;

  6. import io.netty.util.concurrent.ScheduledFuture;

  7. import org.slf4j.Logger;

  8. import org.slf4j.LoggerFactory;

  9.  
  10. import java.util.HashMap;

  11. import java.util.Map;

  12. import java.util.concurrent.TimeUnit;

  13.  
  14. /**

  15. * Created by RoyDeng on 17/7/20.

  16. */

  17. public class LiveHandler extends SimpleChannelInboundHandler<LiveMessage> { // 1

  18.  
  19. private static Map<Integer, LiveChannelCache> channelCache = new HashMap<>();

  20. private Logger logger = LoggerFactory.getLogger(LiveHandler.class);

  21.  
  22. @Override

  23. protected void channelRead0(ChannelHandlerContext ctx, LiveMessage msg) throws Exception {

  24. Channel channel = ctx.channel();

  25. final int hashCode = channel.hashCode();

  26. System.out.println("channel hashCode:" + hashCode + " msg:" + msg + " cache:" + channelCache.size());

  27.  
  28. if (!channelCache.containsKey(hashCode)) {

  29. System.out.println("channelCache.containsKey(hashCode), put key:" + hashCode);

  30. channel.closeFuture().addListener(future -> {

  31. System.out.println("channel close, remove key:" + hashCode);

  32. channelCache.remove(hashCode);

  33. });

  34. ScheduledFuture scheduledFuture = ctx.executor().schedule(

  35. () -> {

  36. System.out.println("schedule runs, close channel:" + hashCode);

  37. channel.close();

  38. }, 10, TimeUnit.SECONDS);

  39. channelCache.put(hashCode, new LiveChannelCache(channel, scheduledFuture));

  40. }

  41.  
  42. switch (msg.getType()) {

  43. case LiveMessage.TYPE_HEART: {

  44. LiveChannelCache cache = channelCache.get(hashCode);

  45. ScheduledFuture scheduledFuture = ctx.executor().schedule(

  46. () -> channel.close(), 5, TimeUnit.SECONDS);

  47. cache.getScheduledFuture().cancel(true);

  48. cache.setScheduledFuture(scheduledFuture);

  49. ctx.channel().writeAndFlush(msg);

  50. break;

  51. }

  52. case LiveMessage.TYPE_MESSAGE: {

  53. channelCache.entrySet().stream().forEach(entry -> {

  54. Channel otherChannel = entry.getValue().getChannel();

  55. otherChannel.writeAndFlush(msg);

  56. });

  57. break;

  58. }

  59. }

  60. }

  61.  
  62. @Override

  63. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

  64. logger.debug("channelReadComplete");

  65. super.channelReadComplete(ctx);

  66. }

  67.  
  68. @Override

  69. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

  70. logger.debug("exceptionCaught");

  71. if(null != cause) cause.printStackTrace();

  72. if(null != ctx) ctx.close();

  73. }

  74. }

  75.  
  76.  

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

 
  1. package com.dz.test;

  2.  
  3. import org.slf4j.Logger;

  4. import org.slf4j.LoggerFactory;

  5.  
  6. import java.io.IOException;

  7. import java.net.InetSocketAddress;

  8. import java.net.Socket;

  9. import java.nio.ByteBuffer;

  10. import java.util.Scanner;

  11.  
  12. /**

  13. * Created by RoyDeng on 18/2/3.

  14. */

  15. public class LongConnTest {

  16.  
  17. private Logger logger = LoggerFactory.getLogger(LongConnTest.class);

  18.  
  19. String host = "localhost";

  20. int port = 8080;

  21.  
  22. public void testLongConn() throws Exception {

  23. logger.debug("start");

  24. final Socket socket = new Socket();

  25. socket.connect(new InetSocketAddress(host, port));

  26. Scanner scanner = new Scanner(System.in);

  27. new Thread(() -> {

  28. while (true) {

  29. try {

  30. byte[] input = new byte[64];

  31. int readByte = socket.getInputStream().read(input);

  32. logger.debug("readByte " + readByte);

  33. } catch (IOException e) {

  34. e.printStackTrace();

  35. }

  36. }

  37. }).start();

  38. int code;

  39. while (true) {

  40. code = scanner.nextInt();

  41. logger.debug("input code:" + code);

  42. if (code == 0) {

  43. break;

  44. } else if (code == 1) {

  45. ByteBuffer byteBuffer = ByteBuffer.allocate(5);

  46. byteBuffer.put((byte) 1);

  47. byteBuffer.putInt(0);

  48. socket.getOutputStream().write(byteBuffer.array());

  49. logger.debug("write heart finish!");

  50. } else if (code == 2) {

  51. byte[] content = ("hello, I'm" + hashCode()).getBytes();

  52. ByteBuffer byteBuffer = ByteBuffer.allocate(content.length + 5);

  53. byteBuffer.put((byte) 2);

  54. byteBuffer.putInt(content.length);

  55. byteBuffer.put(content);

  56. socket.getOutputStream().write(byteBuffer.array());

  57. logger.debug("write content finish!");

  58. }

  59. }

  60. socket.close();

  61. }

  62.  
  63. // 因为Junit不支持用户输入,所以用main的方式来执行用例

  64. public static void main(String[] args) throws Exception {

  65. new LongConnTest().testLongConn();

  66. }

  67. }

  68.  

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

结语

​ 本项目是我一直想研究的一块,这个demo比较简单,不能投入到生产环境中去,因为不能应付连接数大的应用场景。本项目已经上传至github,地址:https://github.com/dzr1990/helloNetty/tree/master,如果有问题欢迎评论留言!

前三篇笔记的快捷通道:

--------------------- 本文来自 帅性而为1号 的优快云 博客 ,全文地址请点击:https://blog.youkuaiyun.com/zhushuai1221/article/details/79709643?utm_source=copy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值