HTTP和MQTT的简单应用

一、HTTP应用的两个实例(Java):

a、读取指定城市的天气预报信息

两个例子的关键是接收来自网页的数据,

定义URL对象:

URL url = new URL("https://api.XXX"+XXX);

新建getweather包,再新建Getweather类:

在这里插入图片描述
写入以下代码:

package getweather;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.io.ObjectInputStream;
import java.util.regex.*;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;


public class Getweather {
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		String weather=URLEncoder.encode("重庆天气","UTF-8");
		//1. 	先准备一个URL类的对象 u
		URL url = new URL("https://api.jisuapi.com/iqa/query?appkey=62958a3a6ef3c56d&question="+weather);
		//2. 	打开服务器连接,得到连接对象 conn
		URLConnection conn = url.openConnection();
		//3. 	获取加载数据的字节输入流 is
		InputStream is = conn.getInputStream();
		//4.	将is装饰为能一次读取一行的字符输入流 br
		BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
		//5.	加载一行数据
		String text = br.readLine();
		//6.	显示		
		//截取相关内容
		int i=text.indexOf("content");
		int j=text.indexOf("relquestion");
		String text1=text.substring(i+10, j-3);
		int m=text1.indexOf("<5.4m\\/s\\r\\n");
		String text2="";
		text2=text1.substring(m+12, text1.length());
		text1=text1.substring(0, m);
		System.out.println(text1);
		System.out.println(text2);
		//7.	释放资源	
		br.close();
	}
}

点击编译运行,结果展示如图所示:

在这里插入图片描述

b、给指定手机号码发送验证码

同样,找到相关的API开发平台或者运营公司:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

public class SendMessage {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		//关键使用步骤:
		//1. 	先准备一个URL类的对象 u
		URL url = new URL("https://itdage.com/kkb/kkbsms?key=xzk&number=要发送信息的目的电话号码&code=8888");
		//2. 	打开服务器连接,得到连接对象 conn
		URLConnection conn = url.openConnection();
		//3. 	获取加载数据的字节输入流 is
		InputStream is = conn.getInputStream();
		//4.	将is装饰为能一次读取一行的字符输入流 br
		BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
		//5.	加载一行数据
		String text = br.readLine();
		//6.	显示
		System.out.println(text);
		//7.	释放资源
		br.close();
	}
}

运行结果如下所示:
在这里插入图片描述

二、MQTT的简单学习:

a、天气预报的消息主题

下载安装Apollo;

链接: http://127.0.0.1:61680.

进入apollo的登录页面

第一次输入Username=admin,Password=password。但是,第二次登陆的时候,就无法再次登录。可以输入https://127.0.0.1:61681,进行再次登录。

搭建好服务器之后,下载客户端之后:

在这里插入图片描述
进行服务器连接:

在这里插入图片描述
效果如下所示:

在这里插入图片描述

b、编写MQTT客户端程序(C#)

免费MQTT参考如下:

在这里插入图片描述

新建项目:

在这里插入图片描述
客户端代码:

using MQTTnet;
using MQTTnet.Core;
using MQTTnet.Core.Client;
using MQTTnet.Core.Packets;
using MQTTnet.Core.Protocol;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MqttClientWin
{
    public partial class FmMqttClient : Form
    {
        private MqttClient mqttClient = null;

        public FmMqttClient()
        {
            InitializeComponent();

            Task.Run(async () => { await ConnectMqttServerAsync(); });
        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <returns></returns>
        private async Task ConnectMqttServerAsync()
        {
            if (mqttClient == null)
            {
                mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient;
                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
                mqttClient.Connected += MqttClient_Connected;
                mqttClient.Disconnected += MqttClient_Disconnected;

            }

            try
            {
                var options = new MqttClientTcpOptions
                {
                    Server = "127.0.0.1",
                    //Server = "172.16.30.77",
                    ClientId = Guid.NewGuid().ToString().Substring(0, 5),
                    UserName = "u001",
                    Password = "p001",
                    CleanSession = true
                };

                await mqttClient.ConnectAsync(options);
             
            }
            catch (Exception ex)
            {
                Invoke((new Action(() =>
                {
                    txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
                })));
            }
        }

        /// <summary>
        /// 服务器连接成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MqttClient_Connected(object sender, EventArgs e)
        {
            Invoke((new Action(() =>
            {
                txtReceiveMessage.AppendText("已连接到MQTT服务器!" + Environment.NewLine);
            })));
        }

        /// <summary>
        /// 断开服务器连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MqttClient_Disconnected(object sender, EventArgs e)
        {
            Invoke((new Action(() =>
            {
                txtReceiveMessage.AppendText("已断开MQTT连接!" + Environment.NewLine);
            })));
        }

        /// <summary>
        /// 接收到消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            Invoke((new Action(() =>
            {
                txtReceiveMessage.AppendText($">> {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
            })));
        }

        /// <summary>
        /// 订阅消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSubscribe_ClickAsync(object sender, EventArgs e)
        {
            string topic = txtSubTopic.Text.Trim();

            if (string.IsNullOrEmpty(topic))
            {
                MessageBox.Show("订阅主题不能为空!");
                return;
            }

            if (!mqttClient.IsConnected)
            {
                MessageBox.Show("MQTT客户端尚未连接!");
                return;
            }

            mqttClient.SubscribeAsync(new List<TopicFilter> {
                new TopicFilter(topic, MqttQualityOfServiceLevel.AtMostOnce)
            });

            txtReceiveMessage.AppendText($"已订阅[{topic}]主题" + Environment.NewLine);
            txtSubTopic.Enabled = false;
            btnSubscribe.Enabled = false;
        }

        /// <summary>
        /// 发布主题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnPublish_Click(object sender, EventArgs e)
        {
            string topic = txtPubTopic.Text.Trim();

            if (string.IsNullOrEmpty(topic))
            {
                MessageBox.Show("发布主题不能为空!");
                return;
            }

            string inputString = txtSendMessage.Text.Trim();
            var appMsg = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);
            mqttClient.PublishAsync(appMsg);
        }

        private void FmMqttClient_Load(object sender, EventArgs e)
        {
            //Dictionary<string, string> dic = new Dictionary<string, string>();
            //dic.Add("ClientId", "123");
            //dic.Add("Topic", "ttt");
            //dic.Add("Value", "ggyy");
            //dic.Add("ServiceLevel", "1");
            //TopicLogic.SaveTopic(dic);
        }
    }
}

服务端代码:

using MQTTnet;
using MQTTnet.Core.Adapter;
using MQTTnet.Core.Diagnostics;
using MQTTnet.Core.Protocol;
using MQTTnet.Core.Server;
using System;
using System.Text;
using System.Threading;
 
namespace MqttServerTest
{
    class Program
    {
        private static MqttServer mqttServer = null;
 
        static void Main(string[] args)
        {
            MqttNetTrace.TraceMessagePublished += MqttNetTrace_TraceMessagePublished;
            new Thread(StartMqttServer).Start();
 
            while (true)
            {
                var inputString = Console.ReadLine().ToLower().Trim();
 
                if (inputString == "exit")
                {
                    mqttServer?.StopAsync();
                    Console.WriteLine("MQTT服务已停止!");
                    break;
                }
                else if (inputString == "clients")
                {
                    foreach (var item in mqttServer.GetConnectedClients())
                    {
                        Console.WriteLine($"客户端标识:{item.ClientId},协议版本:{item.ProtocolVersion}");
                    }
                }
                else
                {
                    Console.WriteLine($"命令[{inputString}]无效!");
                }
            }
        }
 
        private static void StartMqttServer()
        {
            if (mqttServer == null)
            {
                try
                {
                    var options = new MqttServerOptions
                    {
                        ConnectionValidator = p =>
                        {
                            if (p.ClientId == "c001")
                            {
                                if (p.Username != "u001" || p.Password != "p001")
                                {
                                    return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                                }
                            }
 
                            return MqttConnectReturnCode.ConnectionAccepted;
                        }
                    };
 
                    mqttServer = new MqttServerFactory().CreateMqttServer(options) as MqttServer;
                    mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
                    mqttServer.ClientConnected += MqttServer_ClientConnected;
                    mqttServer.ClientDisconnected += MqttServer_ClientDisconnected;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }
 
            mqttServer.StartAsync();
            Console.WriteLine("MQTT服务启动成功!");
        }
 
        private static void MqttServer_ClientConnected(object sender, MqttClientConnectedEventArgs e)
        {
            Console.WriteLine($"客户端[{e.Client.ClientId}]已连接,协议版本:{e.Client.ProtocolVersion}");
        }
 
        private static void MqttServer_ClientDisconnected(object sender, MqttClientDisconnectedEventArgs e)
        {
            Console.WriteLine($"客户端[{e.Client.ClientId}]已断开连接!");
        }
 
        private static void MqttServer_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            Console.WriteLine($"客户端[{e.ClientId}]>> 主题:{e.ApplicationMessage.Topic} 负荷:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)} Qos:{e.ApplicationMessage.QualityOfServiceLevel} 保留:{e.ApplicationMessage.Retain}");
        }
 
        private static void MqttNetTrace_TraceMessagePublished(object sender, MqttNetTraceMessagePublishedEventArgs e)
        {
            /*Console.WriteLine($">> 线程ID:{e.ThreadId} 来源:{e.Source} 跟踪级别:{e.Level} 消息: {e.Message}");
            if (e.Exception != null)
            {
                Console.WriteLine(e.Exception);
            }*/
        }
    }
}

运行结果如下:

在这里插入图片描述

参考自:
https://www.cnblogs.com/Xieyingpeng/p/14136042.html.
https://blog.csdn.net/qq_43279579/article/details/111873008.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值