2018年2月 的存档
20182 月26

利用nutz+t-io实现硬件设备的socket通信

 

1、MainServer 启动类

/**
 * Created by Wizzer on 2018/2/26.
 */
@IocBean
public class MainServer {
    private static final Log log = Logs.get();

    public static void main(String[] args) {
        try {
            ComboIocLoader loader = new ComboIocLoader(
                    new String[]{"*json", "config/ioc/", "*anno", "cn.wizzer","*rabbitmq"}
            );
            NutIoc ioc = new NutIoc(loader);
            //socket
            ioc.get(SocketServer.class).init();
            //http
            ioc.get(HttpServer.class).init();
            //mq
            String topicQueue = "sweeper-tioTopicQueue";
            ConnectionFactory factory = ioc.get(ConnectionFactory.class, "rabbitmq_cf");
            Connection rabbitmq_conn = factory.newConnection();
            Channel rabbitmq_channel = rabbitmq_conn.createChannel();
            rabbitmq_channel.queueDeclare(topicQueue, true, false, false, null);
            rabbitmq_channel.exchangeDeclare("sweeper-tioTopicExchange", BuiltinExchangeType.TOPIC, true);
            rabbitmq_channel.queueBind(topicQueue, "sweeper-tioTopicExchange", "tio.#");


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

2、SocketServer 数据接收

 

/**
 * Created by Wizzer on 2018/2/26.
 */
@IocBean
public class SocketServer {
    private static final Log log = Logs.get();
    //handler, 包括编码、解码、消息处理
    @Inject
    private MyServerAioHandler myServerAioHandler;
    //事件监听器,可以为null,但建议自己实现该接口,可以参考showcase了解些接口
    private ServerAioListener aioListener;
    //一组连接共用的上下文对象
    private ServerGroupContext serverGroupContext;
    //aioServer对象
    private AioServer aioServer;
    //有时候需要绑定ip,不需要则null
    private String serverIp;
    @Inject
    private PropertiesProxy conf;

    public void init() throws Exception {
        int port = conf.getInt("server.socket.port", 8600);
        log.debug("socket port::" + port);
        serverGroupContext = new ServerGroupContext("tio", myServerAioHandler, aioListener);
        serverGroupContext.setHeartbeatTimeout(30000);
        aioServer = new AioServer(serverGroupContext);
        aioServer.start(serverIp, port);
    }
}

3、socket 数据包的解析

4、RabbitMQ 队列+消费者 实现数据入库

5、HttpServer 提供HTTP API用于对设备发送命令

6、socket 命令包的下发

 

源码:https://gitee.com/wizzer/demo