//以下是C# MES对接的示例代码:
//1. MQTT
//使用M2Mqtt库实现C#与MQTT的通信,示例代码如下:
//csharp
using System;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
class Program
{
static void Main(string[] args)
{
// 创建MQTT客户端实例
MqttClient client = new MqttClient("localhost");
// 注册连接事件
client.MqttMsgConnected += Client_MqttMsgConnected;
// 注册消息接收事件
client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
// 连接到MQTT服务器
client.Connect(Guid.NewGuid().ToString());
// 订阅主题
client.Subscribe(new string[] { "test" },
new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE }
);
// 发布消息
client.Publish("test", Encoding.UTF8.GetBytes("Hello, MQTT!"));
}
private static void Client_MqttMsgConnected(object sender, MqttMsgConnectEventArgs e)
{
Console.WriteLine("Connected to MQTT broker.");
}
private static void Client_MqttMsgPublishReceived(object sender,
MqttMsgPublishEventArgs e)
{
Console.WriteLine("Received message: " + Encoding.UTF8.GetString(e.Message));
}
}
//
//2. Restful
//使用HttpClient库实现C#与Restful的通信,示例代码如下:
//csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 创建HttpClient实例
HttpClient client = new HttpClient();
// 发送GET请求
HttpResponseMessage response = await client.GetAsync("http://localhost:8080/api/test");
// 获取响应内容
string content = await response.Content.ReadAsStringAsync();
// 输出响应内容
Console.WriteLine(content);
}
}
//
//3. RabbitMQ
//使用RabbitMQ.Client库实现C#与RabbitMQ的通信,示例代码如下:
//csharp
using System;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
class Program
{
static void Main(string[] args)
{
// 创建RabbitMQ连接工厂
ConnectionFactory factory = new ConnectionFactory()
{
HostName = "localhost",
UserName = "guest",
Password = "guest"
};
// 创建RabbitMQ连接
using (IConnection connection = factory.CreateConnection())
{
// 创建RabbitMQ通道
using (IModel channel = connection.CreateModel())
{
// 定义队列
channel.QueueDeclare(queue: "test",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
// 注册消息接收事件
EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
byte[] body = ea.Body.ToArray();
string message = Encoding.UTF8.GetString(body);
Console.WriteLine("Received message: " + message);
};
channel.BasicConsume(queue: "test",
autoAck: true,
consumer: consumer);文章来源:https://www.toymoban.com/news/detail-490439.html
// 发布消息
string message = "Hello, RabbitMQ!";
byte[] body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "test",
basicProperties: null,
body: body);
}
}
}
}
//文章来源地址https://www.toymoban.com/news/detail-490439.html
到了这里,关于c# MES 对接之二(MQTT、Restful、RabbitMQ)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!