package io.mqtt.server;

import io.mqtt.tool.ConfigService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import io.netty.util.internal.logging.Log4JLoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class Server {
    private static final InternalLogger logger = InternalLoggerFactory
            .getInstance(Server.class);

private int port;
    //    private final int port = ConfigService.getIntProperty("tcp.port", 1883);
    private final int httpPort = ConfigService
            .getIntProperty("http.port", 8080);

private List<Channel> channels = new ArrayList<Channel>();
    private EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private EventLoopGroup workerGroup = new NioEventLoopGroup();

public Server(int port) {
        this.port = port;
    }

private ServerBootstrap getDefaultServerBootstrap() {
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup)
                .option(ChannelOption.SO_BACKLOG, 1000)
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        return server;
    }

public ChannelFuture run() throws Exception {
        InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory());

Channel channle = getDefaultServerBootstrap()
                .childHandler(new TcpChannelInitializer()).bind(port).sync()
                .channel();
        channels.add(channle);

logger.info("mqtt.io tcp server started at port " + port + '.');

ChannelFuture future = getDefaultServerBootstrap().childHandler(
                new HttpChannelInitializer()).bind(httpPort);

Channel httpChannel = future.sync().channel();
        channels.add(httpChannel);

logger.info("mqtt.io websocket server started at port " + httpPort
                + '.');

return future;
    }

public void destroy() {
        logger.info("destroy mqtt.io server ...");
        for (Channel channel : channels) {
            channel.close();
        }
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

public static void main(String[] args) throws Exception {
//        for (int i = 0; i < 5; i++) {
            new ServerThread(65432 + (0 * 2)).start();
//        }
    }

}

package io.mqtt.handler;

import io.mqtt.processer.ConnectProcesser;
import io.mqtt.processer.DisConnectProcesser;
import io.mqtt.processer.PingReqProcesser;
import io.mqtt.processer.PublishProcesser;
import io.mqtt.processer.SubscribeProcesser;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.ReadTimeoutException;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import io.mqtt.processer.*;
import org.meqantt.message.ConnAckMessage;
import org.meqantt.message.ConnAckMessage.ConnectionStatus;
import org.meqantt.message.DisconnectMessage;
import org.meqantt.message.Message;
import org.meqantt.message.Message.Type;
import org.meqantt.message.PingRespMessage;

public class MqttMessageHandler extends ChannelInboundHandlerAdapter {
    private static PingRespMessage PINGRESP = new PingRespMessage();

private static final Map<Message.Type, Processer> processers;
    static {
        Map<Message.Type, Processer> map = new HashMap<Message.Type, Processer>(
                6);

map.put(Type.CONNECT,  new ConnectProcesser());
        map.put(Type.PUBLISH,  new PublishProcesser());
        map.put(Type.SUBSCRIBE, (Processer) new SubscribeProcesser());
        map.put(Type.UNSUBSCRIBE, (Processer) new UnsubscribeProcesser());
        map.put(Type.PINGREQ, new PingReqProcesser());
        map.put(Type.DISCONNECT, (Processer) new DisConnectProcesser());

processers = Collections.unmodifiableMap(map);
    }

@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable e)
            throws Exception {
        try {
            if (e.getCause() instanceof ReadTimeoutException) {
                ctx.write(PINGRESP).addListener(
                        ChannelFutureListener.CLOSE_ON_FAILURE);
            } else {
                ctx.channel().close();
            }
        } catch (Throwable t) {
            t.printStackTrace();
            ctx.channel().close();
        }

e.printStackTrace();
    }

@Override
    public void channelRead(ChannelHandlerContext ctx, Object obj)
            throws Exception {
        //MQTT MESSAGE
        Message msg = (Message) obj;
        // server收到clinet 的MQTT数据包,并获取MQTT的消息类型
        Processer p = processers.get(msg.getType());
        if (p == null) {
            return;
        }
        //根据特定消息类型解析消息包
        Message rmsg = p.proc(msg, ctx);
        if (rmsg == null) {
            return;
        }
        //根据消息处理结果,向clinet做出回应
        if (rmsg instanceof ConnAckMessage
                && ((ConnAckMessage) rmsg).getStatus() != ConnectionStatus.ACCEPTED) {
            ctx.write(rmsg).addListener(ChannelFutureListener.CLOSE);
        } else if (rmsg instanceof DisconnectMessage) {
            ctx.write(rmsg).addListener(ChannelFutureListener.CLOSE);
        } else {
            ctx.write(rmsg).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        }
    }

@Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}

//client

package com.test.client;

import org.eclipse.paho.client.mqttv3.*;

public class SubscribeMessage implements MqttCallback {

private MqttClient client;

public SubscribeMessage() {
    }

public static void main(String[] args) {
//        String tcpUrl = "tcp://127.0.0.1:1883";
//        String clientId = "sub-msg/client1";
//        String topicName = "sub/client1";
//
//        new SubscribeMessage().doDemo(tcpUrl, clientId, topicName);
//        for (int j = 0; j < 5; j++) {
            for (int i = 0; i < 10000; i++) {
        new SubscribeThread("client_" + 0 + i, "tcp://127.0.0.1:" + (65432 + 0 * 2)).start();
            }
//        }

}

public void doDemo(String tcpUrl, String clientId, String topicName) {
        try {
            client = new MqttClient(tcpUrl, clientId);
            MqttConnectOptions mqcConf = new MqttConnectOptions();
            mqcConf.setConnectionTimeout(300);
            mqcConf.setKeepAliveInterval(1000);
            client.connect(mqcConf);
            client.setCallback(this);
            client.subscribe(topicName);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

public void connectionLost(Throwable cause) {
        cause.printStackTrace();
    }

public void messageArrived(String topic, MqttMessage message)
            throws Exception {
        System.out.println("[GOT PUBLISH MESSAGE] : " + message);
    }

public void deliveryComplete(IMqttDeliveryToken token) {
    }
}

netty+mqtt的更多相关文章

  1. tcp 高性能服务, netty,mqtt

    1. io 线程不要有比较长的服务. 全部异步化. [1] netty 权威指南上只是说业务复杂时派发到业务线程池种. 共用的线程池最好都轻量. 多层线程池后, 下层的可以进行隔离. 这个是 mqtt ...

  2. 一篇关于Maven项目的jar包Shell启动脚本

    使用Maven作为项目jar包依赖的管理,常常会遇到命令行启动,笔者也是哥菜鸟,在做微服务,以及服务器端开发的过程中,常常会遇到项目的启动需要使用main方法,笔者潜心的研究了很多博客,发现大多写的都 ...

  3. spring系列框架篇-承接各类型中小型项目-期待与您的长期合作!

    框架选型: 1.基本框架:springboot2.2+springcloud(Hoxton.M2)+nacos (所有公共模块全部使用 starter 方式依赖) 2.授权及权限:oauth2+jwt ...

  4. Netty实现高性能IOT服务器(Groza)之手撕MQTT协议篇上

    前言 诞生及优势 MQTT由Andy Stanford-Clark(IBM)和Arlen Nipper(Eurotech,现为Cirrus Link)于1999年开发,用于监测穿越沙漠的石油管道.目标 ...

  5. 基于Netty的IdleStateHandler实现Mqtt心跳

    基于Netty的IdleStateHandler实现Mqtt心跳 IdleStateHandler解析 最近研究jetlinks编写的基于Netty的mqtt-client(https://githu ...

  6. Netty系列之Netty百万级推送服务设计要点

    1. 背景 1.1. 话题来源 最近很多从事移动互联网和物联网开发的同学给我发邮件或者微博私信我,咨询推送服务相关的问题.问题五花八门,在帮助大家答疑解惑的过程中,我也对问题进行了总结,大概可以归纳为 ...

  7. Netty_Netty系列之Netty百万级推送服务设计要点

    1. 背景 1.1. 话题来源 最近很多从事移动互联网和物联网开发的同学给我发邮件或者微博私信我,咨询推送服务相关的问题.问题五花八门,在帮助大家答疑解惑的过程中,我也对问题进行了总结,大概可以归纳为 ...

  8. 【netty】Netty系列之Netty百万级推送服务设计要点

    1. 背景 1.1. 话题来源 最近很多从事移动互联网和物联网开发的同学给我发邮件或者微博私信我,咨询推送服务相关的问题.问题五花八门,在帮助大家答疑解惑的过程中,我也对问题进行了总结,大概可以归纳为 ...

  9. Netty版本升级血泪史之线程篇

    1. 背景 1.1. Netty 3.X系列版本现状 根据对Netty社区部分用户的调查,结合Netty在其它开源项目中的使用情况,我们可以看出目前Netty商用的主流版本集中在3.X和4.X上,其中 ...

随机推荐

  1. vary的用法

    对于vary的用法,网上有许多种说法,云里雾里的,在此仅阐述一下本人的一些理解,首先是官方解释: Vary头域值指定了一些请求头域,这些请求头域用来决定: 当缓存中存在一个响应,并且该缓存没有过期失效 ...

  2. nginx rewrite标签配置以及用户认证配置

    一.nginx  rewrite标签 rewrite 实现URL的改写主要是实现伪静态 1.  rewrite指令语法 指令语法:rewrite regex replacement[flag] 默认值 ...

  3. apache中配置php支持模块模式、cgi模式和fastcgi模式的实验

    首先安装apache.mysql和php,依次顺序安装. 1.apache.mysql的安装比较简单,略过 2. php的安装,我安装的是php5.3.6内置了php-fpm,所以不需要再单独下补丁了 ...

  4. Spring Cloud之Feigin客户端重构思想

    应该重构接口信息(重点) toov5-parent  存放共同依赖信息 toov5-api       api的只有接口没有实现 toov5-api-member toov5-api-order to ...

  5. Spring Cloud之Eureka自我保护环境搭建

    Eureka详解 服务消费者模式 获取服务 消费者启动的时候,使用服务别名,会发送一个rest请求到服务注册中心获取对应的服务信息,让后会缓存到本地jvm客户端中,同时客户端每隔30秒从服务器上更新一 ...

  6. sqoop导入增量数据

    使用sqoop导入增量数据. 核心参数 --check-column 用来指定一些列,这些列在增量导入时用来检查这些数据是否作为增量数据进行导入,和关系行数据库中的自增字段及时间戳类似这些被指定的列的 ...

  7. Qt中 QTableWidget用法总结

    转自--> http://edsionte.com/techblog/archives/3014 http://hi.baidu.com/fightiger/item/693aaa0f0f87d ...

  8. codeforces 707D:Persistent Bookcase

    Description Recently in school Alina has learned what are the persistent data structures: they are d ...

  9. spring学习(3)

    bean的声明周期 为什么把生命周期当做一个重点? Servlet->servlet生命周期 Servlet生命周期分为三个阶段: 1:初始化阶段,调用init()方法 2:响应客户请求阶段,调 ...

  10. Spring4面向切面AOP

    AOP(Aspect Oriented Programming)面向切面编程,通过预编译方式和运行期动态代理实现程序功能的横向多模块统一控制的一种技术.AOP是OOP的补充,是spring框架中的一个 ...