# 五.补充功能(消息推送)
前言
前端主要有三种方式实现信息实时更新:页面实时更新内容比较多时才使用WebSocket
- 1.轮询:通过定时器不断请求接口
- 2.长轮询:后端只有更新消息才会返回
- 3.WebSocket
# 1.WebSocket
# 2.Server-Sent Events
# 3.Long Polling
刷新
全屏/自适应
# 4.WebRTC
# 5.Comet
刷新
全屏/自适应
# 6.SignalR
:::
<template>
<div>
<input v-model="user" type="text" />
<input v-model="message" type="text" /><br />
<button @click="sendMsg">发送</button>
<hr />
<ul>
<li v-for="(item, index) in msgList" :key="index">
{{ item.user }}: {{ item.msg }}
</li>
</ul>
</div>
</template>
<script>
const signalR = require("@microsoft/signalr")
export default {
data() {
return {
connection: "",
user: "",
message: "",
msgList: [],
}
},
created() {
this.init()
},
methods: {
init() {
this.connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:5000/chathub", {})
.configureLogging(signalR.LogLevel.Error)
.build()
this.connection.on("ReceiveMessage", (data) => {
this.msgList.push(data)
})
this.connection.start()
},
sendMsg() {
let params = {
user: this.user,
message: this.message,
}
this.connection.invoke("SendMessage", params)
},
},
}
</script>
<style></style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
:::
# 7.MQTT
:::
<template>
<div id="app">
<p>mqtt收到的数据:</p>
<p>{{ this.msg }}</p>
</div>
</template>
<script>
import mqtt from "mqtt"
var client
const options = {
connectTimeout: 40000,
clientId: "mqtitId-Home",
username: "admin",
password: "admin123",
clean: true,
}
client = mqtt.connect("ws://172.80.5.222:8083/mqtt", options)
export default {
data() {
return {
msg: "--",
}
},
created() {
this.mqttMsg()
},
methods: {
mqttMsg() {
client.on("connect", (e) => {
console.log("连接成功!!!")
client.subscribe("/wjw1014", { qos: 0 }, (error) => {
if (!error) {
console.log("订阅成功")
} else {
console.log("订阅失败")
}
})
})
// 接收消息处理
client.on("message", (topic, message) => {
console.log("收到来自", topic, "的消息", message.toString())
this.msg = message.toString()
})
},
},
}
</script>
<style scoped></style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
:::