核心是这个东西 this.connection.on("ReceiveMessage"
必须叫ReceiveMessage
import { HubConnectionBuilder, HubConnectionState } from "@microsoft/signalr";
created:{
this.connect();
},
methods:{
connect() {
let url = `${process.env.VUE_APP_BASE_API}/signalr-hubs/chat`;
let token = store.getters.token.replace("Bearer ", "");
const builder = new HubConnectionBuilder();
this.connection = builder
.withUrl(url, {
accessTokenFactory: () => token,
})
.withAutomaticReconnect({ nextRetryDelayInMilliseconds: () => 60000 })
.build();
this.connection.on("ReceiveMessage", (message) => {
console.log(message, "接收信息成功");
});
this.connection.onreconnected((connectionId) => {
console.log(connectionId, "自动重新连接成功");
});
this.connection.onclose((res) => {
console.log("监听关闭", res);
});
if (this.connection.state !== HubConnectionState.Connected) {
this.connection.start().then((res) => {
console.log("启动即时通信成功", res);
});
}
},
send(){
this.connection.send("test", this.msg).then((res) => {
console.log("发送成功", res);
});
}
}
|