Recently, we have been studying the front-end separation of vue+webAPI. In some application scenarios such as front-end timing loop request back-end interface to determine the status, using mqtt for active message push can greatly reduce the pressure on the server interface and improve the efficiency of the system. In addition, we can use mqtt message notification to establish a message notification service independent of the business service system. This service can also be independent of the development language. The client can be either Android or ios, Java or C#, Python, etc. Don't talk much, here I just implement the JS client using mqtt in vue, and the background uses .net WEB API to use c# mqtt client
first step:Installation dependencies
npm install stompjs
runnpm run devAn error may be reported, prompting to install net, and executing commands
npm install --save net
Part 2: Apply stompjs in components
The js part in the component
<script> import Stomp from 'stompjs' ---Configure in configuration filemqttServer address,Account and other information import { MQTT_SERVICE, MQTT_USERNAME, MQTT_PASSWORD } from '../../config/' export default { name: 'entry', data () { return { client: (MQTT_SERVICE) } }, created () { () }, methods: { onConnected: function (frame) { ('Connected: ' + frame) var topic = '/topic/AllCustomer' ---Subscribe to the channel (topic, , ) }, onFailed: function (frame) { ('Failed: ' + frame) }, responseCallback: function (frame) { ('responseCallback msg=>' + ) ---Receive message }, connect: function () { ---initializationmqttClient,And connectmqttServe var clientid = () var headers = { 'login': MQTT_USERNAME, 'passcode': MQTT_PASSWORD, 'client-id': clientid // additional header } (headers, , ) } } } </script>
Configuration File
/** * Configuration file, record fixed parameters in the system */ export const MQTT_SERVICE = 'ws://127.0.0.1:61623/stomp' // mqtt service addressexport const MQTT_USERNAME = 'admin' // mqtt connection usernameexport const MQTT_PASSWORD = 'password' // mqttConnection Password
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.