目录
一、SocketTool
二、串口通信
三、MQTT中间件
一、SocketTool
1、TCP 通信测试:
1)创建 TCP Server
2)创建 TCP Client
- 连接 Socket
4)数据收发
在TCP Server发送数据12345
在 TCP Client 端的 Socket 即可收到数据12345
2. 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);// 创建消息并设置 QoSMqttMessage 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);}}
}