目录
WebSocket
SignalR
SignalR的基本使用
WebSocket
- WebSocket基于TCP协议,支持二进制通信,双工通信。
- 性能和并发能力更强。
- WebSocket独立于HTTP协议,不过我们一般仍然把WebSocket服务器端部署到Web服务器上,因为可以借助HTTP协议完成初始的握手(可选),并且共享HTTP服务器的端口(主要)。
SignalR
- ASP.NET Core SignalR(以下简称SignalR),是.NET Core平台下对WebSocket的封装。
- Hub(集线器),数据交换中心。
SignalR的基本使用
- 创建MyHub.cs继承自Hub
public class MyHub : Hub {public Task SendPublicMessage(string message){string connId = this.Context.ConnectionId;string msgToSend = $"{connId}{DateTime.Now}:{message}";return Clients.All.SendAsync("ReceivePublicMessage", msgToSend);} }
- 注册SignalR、Cors服务,使用Hub中间件,app.MapControllers()之前调app.MapHub<MyHub>("/MyHub")。
string[] urls = new[] { "http://localhost:5173" }; builder.Services.AddCors(options =>options.AddDefaultPolicy(builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowCredentials()));builder.Services.AddSignalR()app.MapHub<MyHub>("/MyHub"); app.MapControllers();
- 前端Vue代码
<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> import { reactive, onMounted } from 'vue'; import * as signalR from '@microsoft/signalr'; let connection; export default {name: 'Login',setup() {//创建响应式对象,userMessage:输入的消息,messages:接收到的消息const state = reactive({ userMessage: "", messages: [] });//按下回车键发送消息,调用SendPublicMessage方法,发送消息,清空输入框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:7181/MyHub').withAutomaticReconnect().build();//开始连接await connection.start();//注册ReceivePublicMessage事件,接收消息,添加到messages数组connection.on('ReceivePublicMessage', msg => {state.messages.push(msg);});});//返回响应式对象和方法return { state, txtMsgOnkeypress };}, } </script>