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);
        }
    }
}
相关推荐
en.en..3 小时前
STM32 定时器预分频器 TIMx_PSC 详解
单片机·嵌入式硬件
碧海银沙音频科技研究院13 小时前
奥克斯老手机电路图
嵌入式硬件
飞奔的瓜牛13 小时前
Kafka 生产实践指南:使用要点、性能优化与运维维护
中间件·性能优化·kafka
希和20271 天前
江科大 51 单片机笔记:DS18B20 温度传感器 + LCD1602 显示代码详解
笔记·单片机·mongodb
不脱发的程序猿1 天前
ESP32制作加热杯垫
嵌入式硬件·物联网·esp32·语音识别
Zwawa1 天前
陀螺仪数据为什么看起来总在动:零偏、噪声和零漂
c语言·单片机·嵌入式
元器件BOM超人2 天前
GD32F130G8U6TR QFN-28 兆易创新超值型Cortex-M3 MCU 解析
单片机·嵌入式硬件
硅农程序猿2 天前
SOC 物理实现: RTL2GDS 系列(二)—Innovus 初始化
人工智能·嵌入式硬件·硬件架构
希和20272 天前
51 单片机学习笔记:LCD1602、独立按键、I2C 与 AT24C02 掉电存储(江科大课程小白笔记)
笔记·单片机·学习
碧海银沙音频科技研究院2 天前
BP寻呼机原理
人工智能·嵌入式硬件