环境 VS2022 WIN10 .NET8 VSCode VUE SignalR
1.安装SignalR客户端库
需要在Vue.js项目中安装SignalR客户端库。可以使用npm或者yarn来安装
npm install @microsoft/signalr
2.创建SignalR服务
创建SignalR服务,以便客户端(Vue.js应用)能够连接并与之通信
<script>
import * as signalR from "@microsoft/signalr";export default {data() {return {connection: null,connected: false,inCall: false,localStream: null,remoteStream: null,peerConnection: null};},mounted() {this.connection = new signalR.HubConnectionBuilder().withUrl("/chathubv").configureLogging(signalR.LogLevel.Information).build();this.connection.start().then(() => {console.log("SignalR Connected");this.connected = true;}).catch((error) => {console.error("SignalR Connection Error: ", error);});},methods: {async startCall() {this.localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });this.$refs.localVideo.srcObject = this.localStream;this.peerConnection = new RTCPeerConnection();this.peerConnection.addStream(this.localStream);this.peerConnection.onaddstream = (event) => {this.remoteStream = event.stream;this.$refs.remoteVideo.srcObject = this.remoteStream;};const offer = await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(offer);this.connection.invoke("SendOffer", offer);this.inCall = true;},async endCall() {this.localStream.getTracks().forEach(track => track.stop());this.remoteStream.getTracks().forEach(track => track.stop());this.peerConnection.close();this.inCall = false;}}
}
</script>
3.处理视频流组件
Vue组件
<template><div id="app"><div v-if="!connected">Connecting to SignalR...</div><div v-else><div v-if="!inCall"><button @click="startCall">Start Call</button></div><div v-else><video ref="localVideo" autoplay></video><video ref="remoteVideo" autoplay></video><button @click="endCall">End Call</button></div></div></div>
</template>
4.服务端信令交换
using Microsoft.AspNetCore.SignalR;namespace WebSignalR
{public class ChatHubv : Hub{public async Task SendOffer(string offer){await Clients.All.SendAsync("ReceiveOffer", offer);}public async Task SendAnswer(string answer){await Clients.All.SendAsync("ReceiveAnswer", answer);}public async Task SendIceCandidate(string candidate){await Clients.All.SendAsync("ReceiveIceCandidate", candidate);}}}
public async Task SendOffer(string offer): 用于接收客户端发送的"offer"信令。
await Clients.All.SendAsync("ReceiveOffer", offer): 在接收到"offer"信令后,会调用 Clients.All.SendAsync 方法将"offer"信令发送给所有连接到当前Hub的客户端。第一个参数是要调用的客户端方法的名称("ReceiveOffer"),第二个参数是要发送的数据(offer)。
5.Runing
this.connection.start() ...
看到 控制台输出 SignalR Connected 说明和SignalR服务器连接上了