SocketTool、串口调试助手、MQTT中间件基础

目录

一、SocketTool

二、串口通信

三、MQTT中间件

一、SocketTool

1、TCP 通信测试:

1)创建 TCP Server

2)创建 TCP Client

  1. 连接 Socket

4)数据收发

在TCP Server发送数据12345

在 TCP Client 端的 Socket 即可收到数据12345

  1. UDP 通信测试:

1)分别创建 UDP Server 和 UDP Client

2)先由 UDP Client 发送数据

UDP Servers 收到数据才能看到对方端口

在 UDP Server 收到过 UDP Client 的数据后,其对方 IP 地址和 UDP 端口均可确定 下来,然后 UDP Server 也可以向 UDP Client 发送数据了

二、串口通信

先创建两个虚拟串口,这里用到了Configure Virtual Serial Port Driver

然后打开串口调试工具,调整串口设置后打开串口COM2

接着在代码里开启另一个串口CMO1

复制代码
import com.fazecast.jSerialComm.SerialPort;
import java.util.Scanner;

public class SerialCommunicationExample {
    public static void main(String[] args) {
        // 尝试打开 COM1 端口,你可以根据需要修改这个值
        SerialPort serialPort = SerialPort.getCommPort("COM1");

        if (serialPort.openPort()) {
            try {
                // 设置串口参数,这些值应与你的设备匹配
                serialPort.setComPortParameters(9600, 8, 1, SerialPort.NO_PARITY);
                serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 2000, 0);

                // 获取用户输入的消息
                Scanner scanner = new Scanner(System.in);
                System.out.print("Enter message to send: ");
                String messageToSend = scanner.nextLine();

                // 发送消息
                serialPort.writeBytes(messageToSend.getBytes(), messageToSend.length());

                // 等待接收到回复(注意:这里可能需要更复杂的逻辑来处理接收数据)
                byte[] buffer = new byte[1024];
                int numRead;
                StringBuilder receivedMessage = new StringBuilder();
                while ((numRead = serialPort.readBytes(buffer, buffer.length)) > 0) {
                    receivedMessage.append(new String(buffer, 0, numRead));
                }

                System.out.println("Received message: " + receivedMessage);

            } catch (Exception ex) {
                System.out.println("Error: " + ex.getMessage());
            } finally {
                // 关闭串口
                if (serialPort.isOpen()) {
                    serialPort.closePort();
                }
            }
        } else {
            System.out.println("Error: Could not open the serial port.");
        }
    }
}

在串口工具COM2发送数据,COM1能收到,COM1发送的在工具里也能接收到

三、MQTT中间件

先启动mqtt服务

然后订阅和推送

复制代码
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class SubscribeSample {
    public static void main(String[] args) {
        String broker = "tcp://localhost:1883";
        String topic = "mqtt/test";
        String username = "emqx";
        String password = "public";
        String clientid = "subscribe_client";
        int qos = 0;

        try {
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            // 连接参数
            MqttConnectOptions options = new MqttConnectOptions();
//            options.setUserName(username);
//            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            // 设置回调
            client.setCallback(new MqttCallback() {

                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost: " + cause.getMessage());
                }

                public void messageArrived(String topic, MqttMessage message) {
                    System.out.println("topic: " + topic);
                    System.out.println("Qos: " + message.getQos());
                    System.out.println("message content: " + new String(message.getPayload()));

                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }

            });
            client.connect(options);
            client.subscribe(topic, qos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class PublishSample {
    public static void main(String[] args) {

        String broker = "tcp://localhost:1883";
        String topic = "mqtt/test";
        String username = "emqx";
        String password = "public";
        String clientid = "publish_client";
        String content = "Hello MQTT";
        int qos = 0;

        try {
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            // 连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            // 设置用户名和密码
//            options.setUserName(username);
//            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            // 连接
            client.connect(options);
            // 创建消息并设置 QoS
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            // 发布消息
            client.publish(topic, message);
            System.out.println("Message published");
            System.out.println("topic: " + topic);
            System.out.println("message content: " + content);
            // 关闭连接
            client.disconnect();
            // 关闭客户端
            client.close();
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }
}
相关推荐
zcmodeltech1 小时前
智能制造教学实训沙盘模型多系统协同控制系统设计:基于STM32与Modbus RTU的工业机器人-智慧工厂-数字孪生全场景联动方案
数据库·stm32·嵌入式硬件·机器人·制造·多分类
程序员与背包客_CoderZ1 小时前
Linux D-Bus通信协议详解:从入门到C/C++编码实战
linux·服务器·c语言·c++·嵌入式硬件·嵌入式软件·dbus
嵌入式阿蔡2 小时前
HAL库 vs LL库 vs 寄存器:到底用哪个?
c语言·stm32·单片机·嵌入式硬件·嵌入式实时数据库
天空'之城4 小时前
单片机基础核心知识点汇总(三)
单片机·嵌入式硬件
嵌入式阿蔡4 小时前
CAN总线入门:从协议帧到STM32实战
c语言·stm32·单片机·嵌入式硬件·嵌入式实时数据库
恒锐丰科技韩生5 小时前
率能 SS8847E|2.7~15V 双通道 H 桥电机驱动 ETSSOP16 散热封装 家电 / 打印 / 舞台灯光专用
嵌入式硬件·硬件工程
离凌寒5 小时前
一、对stm32mp157配置freertos后,任务挂掉无法启动问题总结
stm32·单片机·嵌入式硬件
消失的旧时光-19437 小时前
7-fix补充篇:机器人为什么需要多级控制仲裁?Cloud、Linux 与 MCU 分别管什么
linux·单片机·机器人·仲裁机制·安全保护机制
Hello_Damon_Nikola7 小时前
CH573从入门到精通
c语言·开发语言·单片机·嵌入式硬件
oshan20128 小时前
华大小华HC32F460单片机在线烧录
单片机·嵌入式硬件