Signalr初体验
之前听过Signalr的大名
可以用于Web聊天和站内通知等
不过一直也没有使用过
最近在再跟着杨中科大佬学习
刚好他也讲到了Signalr
做一个学习记录吧
1.首先创建一个WebApi项目
2.新建MyHub类并继承Hub
Hub引用using Microsoft.AspNetCore.SignalR命名空间
创建SendPublicMessage类,用于服务器将消息发送给客户端
public Task SendPublicMessage(string msg)
{
string connId= Context.ConnectionId;
string msgToSend = $“{connId}{DateTime.Now}:{msg}”;
return Clients.All.SendAsync(“ReceivePublicMsg”, msgToSend);
}
3.Program.cs配置文件
builder.Services.AddSignalR();
app.MapHub(“/MyHub”);
不知道为啥< MyHub >这个显示不出来,注意添加泛型使用~
继续添加对于跨域的代码
string[] urls = new[] { “http://localhost:5173” };
builder.Services.AddCors(options =>
options.AddDefaultPolicy(builder => builder.WithOrigins(urls)
.AllowAnyMethod().AllowAnyHeader().AllowCredentials())
);
app.UseCors();
4.前端代码
在你需要创建项目的文件路径上输入cmd
然后在cmd上输入
npm init vue@latest
按照相应的步骤去创建就好了
创建成功后,其他不变,就直接在Helloword界面上改就好了
<template>
<input type="text" v-model="state.userMessage" v-on:keypress="txtMsgOnkeypress"/>
<div><ul>
<li v-for="(msg,index) in state.messages" :key="index">{{msg}}</li>
</ul></div>
</template>
<script setup>
import { ref, reactive,onMounted} from 'vue'
import * as signalR from "@microsoft/signalr";
const state = reactive({
userMessage: '',
messages: []
})
var connection;
const txtMsgOnkeypress = async (e) => {
if (e.key !== 'Enter') return;
else{
await connection.invoke("SendPublicMessage", state.userMessage);//客户端向服务器端发送消息
state.userMessage = '';
}
}
onMounted(() => {
//skipNegotiation 跳过协商 transport指定传输方式
const options = { skipNegotiation: true, transport: signalR.HttpTransportType.WebSockets };
connection = new signalR.HubConnectionBuilder()
.withUrl('https://localhost:7095/MyHub',options)
.withAutomaticReconnect().build();
connection.start();
connection.on("ReceivePublicMsg", (message) => {
//监听服务器端发送过来的消息
state.messages.push(message);
})
})
</script>
<style scoped>
h1 {
font-weight: 500;
font-size: 2.6rem;
position: relative;
top: -10px;
}
h3 {
font-size: 1.2rem;
}
.greetings h1,
.greetings h3 {
text-align: center;
}
@media (min-width: 1024px) {
.greetings h1,
.greetings h3 {
text-align: left;
}
}
</style>
最后运行的效果就是输msg,将输入的消息添加到messages数组中
需要注意的是
监听方法和回调函数都要一致,避免报错