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);
        }
    }
}
相关推荐
qq_2466461918 分钟前
openclaw快速安装-windows版
windows·stm32·单片机
染予2 小时前
13.AD软件操作:原理图如何导入PCB及导入常见错误
嵌入式硬件
小莞尔3 小时前
【51单片机】【protues仿真】 基于51单片机波形发生器系统
c语言·单片机·嵌入式硬件·物联网·51单片机
码农三叔3 小时前
(9-2-01)电源管理与能源系统:能耗分析与功率管理(1)步行能耗估计
人工智能·嵌入式硬件·机器人·人机交互·能源·人形机器人
沐雪架构师3 小时前
LangChain 1.0 内置的Agent中间件详解
中间件·langchain
Polanda。3 小时前
ADC-定时器触发
单片机·嵌入式硬件
Polanda。3 小时前
ADC-常规序列的单通道转换
stm32·单片机·嵌入式硬件
木子啊3 小时前
PHP中间件:ThinkCMF 6.x核心利器解析
开发语言·中间件·php