服务端SignalR支持
// 加入signalR,需要cors支持
builder.Services.AddSignalR();
string[] urls = { "http://localhost:3000" };
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(builder => builder.WithOrigins(urls)
.AllowAnyMethod().AllowAnyHeader().AllowCredentials());
});
app.UseCors();
app.MapHub<MyChatHub>("/hubs/chatroomhub");
public class MyChatHub : Hub
{
public Task SendPublicMessage(string message)
{
string connId = Context.ConnectionId;
string msg = $"{connId} {DateTime.Now}:{message}";
return Clients.All.SendAsync("PublicMessageReceived", msg);
}
}
client端SignalR支持
. 使用yarn管理包,Vue作为client端框架
yarn create @vitejs/app chatroom
npm install @microsoft/signalr
yarn
yarn dev
<template>
<div>
<input type="text" v-model="state.userMessage" v-on:keypress="txtMsgOnkeypress" />
<ul>
<li v-for="(msg,index) in state.messages" :key="index">{{msg}}</li>
</ul>
</div>
</template>
<script>
import { reactive, onMounted } from "vue";
import * as signalR from "@microsoft/signalr";
let connection;
export default {
name: "Login",
setup() {
const state = reactive({ userMessage: "", messages: [] });
const txtMsgOnkeypress = async function (e) {
if (e.keyCode != 13) return;
await connection.invoke("SendPublicMessage", state.userMessage);
state.userMessage = "";
};
onMounted(async function () {
connection = new signalR.HubConnectionBuilder()
.withUrl("https://localhost:7115/hubs/chatroomhub")
.withAutomaticReconnect()
.build();
await connection.start();
connection.on("PublicMessageReceived", (msg) => {
state.messages.push(msg);
});
});
return { state, txtMsgOnkeypress };
},
};
</script>
---------------------------
知道的更多,不知道的也更多
---------------------------